美文网首页
231. Power of Two

231. Power of Two

作者: 西土城小羊 | 来源:发表于2017-03-21 13:16 被阅读6次

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

读题

题目的意思是给定一个整数,需要判断这个数是不是2的次方数,题目中假定了是一个整数,也就不需要考虑[0,1)这种情况了

思路

一开始的想法总是很暴力,采用除2这种方式,但是发现比较麻烦,于是想到了运用位运算,主要的思路是

  • 因为2的整数次幂按照二进制的形式是很有特点的,所有位里面只会出现一次1,可以应用这一点写一个算法判断是不是只有一个1,这就与前面一道判断二进制1的个数是如出一辙了

  • 还有一种思路是看了题解的,只用了一行代码,确实是一种比较不错的思路,就是 n&(n-1)==0 && n>0,因为对于一个正整数n如果它是2的整数次幂,那么n-1的二进制必定是XXXXX1111111这种的形式,那么与运算应该是0,否则将不会出现结果是0的情况

题解

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

思路二

 public boolean isPowerOfTwo(int n) {
    return ((n & (n-1))==0 && n>0);
}

相关文章

网友评论

      本文标题:231. Power of Two

      本文链接:https://www.haomeiwen.com/subject/rexgnttx.html