Power of Two
Total Accepted: 3596 Total Submissions: 11779Given 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.
[思路]
如果是power of two, 则2进制表达中,有且仅有一个1. 可以通过移位来数1的个数, 这里用了一个巧妙的办法, 即判断 N & (N-1) 是否为0.
[CODE]
public class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && ((n & (n - 1)) == 0 );
}
}
本文提供了一种简洁高效的方法来判断一个整数是否为2的幂次方,通过位运算实现。重点在于理解2进制表示中只有单一1位的特性,利用位与操作符及减一操作进行验证。
700

被折叠的 条评论
为什么被折叠?



