leetCode power of two

来源:互联网 发布:python读取dat文件 编辑:程序博客网 时间:2024/05/21 10:51
public class Solution {
    public boolean isPowerOfTwo(int n) {
        int i = 0 ;
        int j = 0 ;
        if(n == 0 )
        return false ;
        while (n !=1 && i ==0){
            i = n % 2 ;
            n = n / 2 ;
        }
        if(n == 1 && i == 0 )
        {
            return true;
         }
         else 
         {
             return false;
             
         }
    }

}

//采用移位的方法

public class Solution {
    public boolean isPowerOfTwo(int n) {
     int cnt = 0 ;
     while(n > 0){
         cnt += (n & 1);
         n >>= 1;
     }
     return cnt == 1 ;
    //  if(cnt == 1){
    //      return true;
    //  }
    //  else {
    //      return false;
    //  }
    }
}

0 0
原创粉丝点击