您的位置:首页 > 其它

Power of Two & Power of Three & Power of Four

2016-07-23 02:59 387 查看
Check Power of 2

Using O(1) time to check whether an integer n is a power of
2
.

Example

For
n=4
, return
true
;

For
n=5
, return
false
;

奇数总是有超过2个1.

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


Check Power of 3

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

Follow up:
Could you do it without using any loop / recursion?

public class Solution {
public boolean isPowerOfThree(int n) {
if (n == 0)    return false;

if (n == 1) return true;

if (n > 1)
return n % 3 == 0 && isPowerOfThree(n / 3);
else
return false;
}
}


Check Power of 4

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.

private boolean smartBit(long num){
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x5555555555555555l) == num);
}


Explanation:

The magic numbers might seem very confusing. But they are not random (obviously!). Let us start with 0X55555555. Binary representation of 5 is 0101. So 0X55555555 has 16 ones, 16 zeros and the ones,zeros take alternate positions.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: