Power of Two (E)
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
题意
判断一个整数是不是2的幂。
思路
见代码。
代码实现
class Solution {
public boolean isPowerOfTwo(int n) {
if (n <= 0) {
return false;
}
while (n % 2 == 0) {
n /= 2;
}
return n == 1;
}
}
本文介绍了一种简单有效的方法来判断一个给定的整数是否可以表示为2的幂次方。通过逐步除以2并检查最终是否等于1,我们可以确定输入是否满足条件。该方法适用于任何正整数,并提供了清晰的解释和示例。

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



