[leetcode #231] Power of Two
1464 ワード
Problem
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2ˣ.
Example 1:
Idea
これは簡単な問題です.与えられた数が2の平方であると判別すればよい.
0以下は2の平方ではないので、すぐにfalseに戻ります.それ以外は、1を2で割って、残りが0でない場合はfalseを返します.最後に1が表示された場合はtrueを返します.
Solution
Reference
https://leetcode.com/problems/power-of-two/
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2ˣ.
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Example 2:Input: n = 16
Output: true
Explanation: 24 = 16
Example 3:Input: n = 3
Output: false
Constraints:・ -2³¹ <= n <= 2³¹ - 1
Follow up: Could you solve it without loops/recursion?Idea
これは簡単な問題です.与えられた数が2の平方であると判別すればよい.
0以下は2の平方ではないので、すぐにfalseに戻ります.それ以外は、1を2で割って、残りが0でない場合はfalseを返します.最後に1が表示された場合はtrueを返します.
Solution
class Solution {
public boolean isPowerOfTwo(int n) {
if (n <= 0)
return false;
while (n > 1) {
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
}
実はもっと解きやすい方法があります.それは….class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && Integer.bitCount(n) == 1;
}
}
bitcountを1つだけチェックすれば、Follow upに示すように再帰的に解くことができます.==Reference
https://leetcode.com/problems/power-of-two/
Reference
この問題について([leetcode #231] Power of Two), 我々は、より多くの情報をここで見つけました https://velog.io/@timevoyage/leetcode-231-Power-of-Twoテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol