LeetCode原题:Power of Two
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.
主要内容:判断数是否为2的幂乘数,即判断是否是等于2的整数次方的整数
解题思想:按最普通的方法将n反复除以2,最后得到2则符合,如果中途出现n为奇数则不符合。注意n的每个范围的判断,不然无法完整通过测试案例
参考C++代码:
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n <= 0) return false;
if(n == 1) return true;
int m = n % 2;
while(n != 2) {
m = n % 2;
n = n / 2;
if(m != 0) break;
}
if (m != 0) {
return false;
} else {
return true;
}
}
};