Power of Two
Question
Given an integer, write a function to determine if it is a power of two.
Analysis
- 2^n的二进制数中只存在一个1,所以利用num&(num-1)==0 可以判断是否为2^n
- Java中可以利用bitcount()
Code
|
|
Power of Three
Question
Given an integer, write a function to determine if it is a power of three.
Analysis
利用log计算,
log3 12=2.26186
int(log3 12)=2
log3 12−int(log3 12)=0.26186
Code
|
|
|
|
Power of Four
Question
Given an integer, write a function to determine if it is a power of four.
Analysis
The basic idea is from power of 2, We can use “n&(n-1) == 0” to determine if n is power of 2. For power of 4, the additional restriction is that in binary form, the only “1” should always located at the odd position. For example, 4^0 = 1, 4^1 = 100, 4^2 = 10000. So we can use “num & 0x55555555==num” to check if “1” is located at the odd position.
Code
|
|
近期评论