パワーオブTwo
テーマの説明:
Given an integer、write a function to determine if it is a power of two.
一つの数が2の完全な平方数ではないかを見てください。
このような数字の問題に対して、まずビット操作Bit Operationを考慮しなければなりません。
一つの数が2の完全な平方数なら、最高位は1、他のビットは0。
一つの方法は、各ビットを確認し、1であればcnt+1、最後にcntが1であるかどうかを判断することである。
コードは以下の通りです
Given an integer、write a function to determine if it is a power of two.
一つの数が2の完全な平方数ではないかを見てください。
このような数字の問題に対して、まずビット操作Bit Operationを考慮しなければなりません。
一つの数が2の完全な平方数なら、最高位は1、他のビットは0。
一つの方法は、各ビットを確認し、1であればcnt+1、最後にcntが1であるかどうかを判断することである。
コードは以下の通りです
public class Solution {
public boolean isPowerOfTwo(int n) {
int cnt = 0;
while (n > 0) {
cnt += (n & 1);
n >>= 1;
}
return cnt == 1;
}
}
にはもう一つの簡単な方法があります。public class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && ((n & (n - 1)) == 0 );
}
}