Tuesday, December 27, 2016

Leetcode/F家/G家 -- Power of Two

Power of Two
https://leetcode.com/problems/power-of-two/

解法1. bit manipulation 
8 (1000)           
7 (0111)     =>  8 & 7 = 0
6 (0110)           7 & 6 = (0110)=6
所以如果是2的n次方,一定会是1000....的格式,和n-1 &操作,应得0

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

解法2: 数学做法

public class Solution {
    public boolean isPowerOfTwo(int n) {
       long val = 1;
       while(val<n){
           val *=2;
       }
       if(val ==(long)n){
           return true;
       }else{
           return false;
       }
    }
}

No comments:

Post a Comment