326. Power of Three
How to identify if an integer is a power of three

Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
Search for a command to run...
How to identify if an integer is a power of three

Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
No comments yet. Be the first to comment.
A simple example of using C++ switch

Two dynamic programming techniques to solve Leetcode 120. Triangle. One has space complexity O(n^2). The other is O(n).

An example of using a sliding window approach and an unordered map to track character positions

A simple C++ solution to Leetcode 1695. Maximum Erasure Value using a sliding window approach and prefix sums.

Strategies to avoid them will help you excel in your following technical interview

Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3^x.
Input: n = 27
Output: true
Explanation: 27 = 3^3.
Input: n = 0
Output: false
Explanation: There is no x where 3^x = 0.
Input: n = -1
Output: false
Explanation: There is no x where 3^x = (-1).
-2^31 <= n <= 2^31 - 1.Follow up: Could you solve it without loops/recursion?
#include <iostream>
using namespace std;
bool isPowerOfThree(int n) {
while (n % 3 == 0 && n > 0) {
n /= 3;
}
return n == 1;
}
int main() {
cout << isPowerOfThree(27) << endl;
cout << isPowerOfThree(0) << endl;
cout << isPowerOfThree(-1) << endl;
}
Output:
1
0
0
Runtime: O(logn).
Extra space: O(1).
A power of three must divide another bigger one, i.e. 3^x | 3^y where 0 <= x <= y.
Because the constraint of the problem is n <= 2^31 - 1, you can choose the biggest power of three in this range to test the others.
It is 3^19 = 1162261467. The next power will exceed 2^31 = 2147483648.
#include <iostream>
using namespace std;
bool isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
int main() {
cout << isPowerOfThree(27) << endl;
cout << isPowerOfThree(0) << endl;
cout << isPowerOfThree(-1) << endl;
}
Output:
1
0
0
Runtime: O(1).
Extra space: O(1).
Thanks for reading. Feel free to share your thought about my content and check out my FREE book “10 Classic Coding Challenges”.