Power of Two & Power of Three & Power of Four

 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?

 1 public class Solution {
 2     public boolean isPowerOfThree(int n) {
 3         if (n == 0)    return false;
 4 
 5         if (n == 1) return true;
 6 
 7         if (n > 1)
 8             return n % 3 == 0 && isPowerOfThree(n / 3);
 9         else
10             return false;
11     }
12 }

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.

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

 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.

posted @ 2016-07-23 02:59  北叶青藤  阅读(195)  评论(0编辑  收藏  举报