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

231. Power ofTwo

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

 
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)));
    }
}

 

 
 
posted @ 2016-06-05 14:21  新一代的天皇巨星  阅读(208)  评论(0编辑  收藏  举报