power of number

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

1
2
3
4
5
public class {
public boolean isPowerOfThree(int n) {
return (n>0)&&Integer.bitcount(n)==1;
}
}

Power of Three

Question

Given an integer, write a function to determine if it is a power of three.

Analysis

Summary in LeetCode Discuss

利用log计算,

log3 12=2.26186
int(log3 12)=2
log3 12−int(log3 12)=0.26186

Log

Code

1
2
3
4
5
public class {
public boolean isPowerOfThree(int n) {
return (n>0)&&(Math.log10(n)/Math.log10(3))%1==0;
}
}
1
2
3
4
5
6
7
8
9
public class {
public boolean isPowerOfThree(int n) {
if (n <= 0) {
return false;
} else {
return Integer.toString(n, 3).matches("10*");
}
}
}

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

1
2
3
4
5
public class {
public boolean isPowerOfThree(int n) {
return (n>0)&&(num&(num-1)==0)&&(num&0x55555555)==num;
}
}