leetcode 231. Power of Two

来源:互联网 发布:数的读法 c语言 编辑:程序博客网 时间:2024/05/20 00:37

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

我的做法很丑陋,先贴上我的代码,再附上别人的代码。这就是美女与野兽。

public class Solution {    public boolean isPowerOfTwo(int n) {        if(n<=0){return false;}        if(n==1){            return true;        }        if(n%2 !=0){            return false;        }        while(n%2 ==0){            if(n==2){                return true;            }            else{            n=n/2;            }        }                return false;    }}
我的代码冗长不简洁,下面在网上看到的别人的方法,很不错。巧妙运用了2的次幂对应的二进制数,只有一个1.

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



0 0
原创粉丝点击