题目来源【Leetcode】
Given an integer, write a function to determine if it is a power of two.
判断一个数是否为2的N次方
方法一:取对数
class Solution {
public:
bool isPowerOfTwo(int n) {
double i = log10(n)/log10(2);
return (i-(int)i) == 0;
}
};
方法二:用二进制的特点
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n&(n-1));
}
};
方法三:用最大的2进制数
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && 4294967296%n == 0;
}
};
本文介绍了三种判断一个整数是否为2的幂的有效方法:通过取对数比较、利用二进制位运算特点以及借助最大2的幂数值进行判断。这些方法简单高效,适用于多种编程场景。
190

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



