Power of Two (231)
Given an integer, write a function to determine if it is a power of three.
Last updated
Was this helpful?
Given an integer, write a function to determine if it is a power of three.
Last updated
Was this helpful?
Approach 1:
We check if n
can be divided by 2. If yes, divide n
by 2 and check it repeatedly.
**Could also implement it recursively however less eficient due to space being used in the call stack
Complexity: O(log(N)time
Approach2 :
Very intuitive using bitcount. If n
is the power of 2, the bit count of n
is 1.
Note that 0b1000...000
is -2147483648
, which is not the power of two, but the bit count is 1.
Time complexity = O(1)
The time complexity of bitCount()
can be done by a fixed number of operations.
More info in .