您的位置:首页 > 其它

231. Power of Two && 342. Power of Four && 326. Power of Three

2016-06-05 14:21 501 查看

231. Power ofTwo

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

Hide Similar Problems

(E) Number of 1 Bits (E) Power of Three (E) Power of Four

public class Solution {
public boolean isPowerOfTwo(int n) {
if(n <= 0)
return false;
return (n & (n-1)) == 0;
}
}


342. Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

public class Solution {
public boolean isPowerOfFour(int num) {
return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;
//0x55555555 is to get rid of those power of 2 but not power of 4
//so that the single 1 bit always appears at the odd position
}
}


326. Power of Three

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

public class Solution {
public boolean isPowerOfThree(int n) {
return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3)));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: