Question
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 == 2x
.
Algorithm
- Utilize bit manipulation.
- if a number is a power of 2, all its digits are 0 except leading 1.
- So there are actually two ways to use this attribute"
- minus 1, all the bits would be flipped and you could use & to see if the result is 0(each filp would be different)
- -x, −x is the same as ~x + 1, This operation reverts all bits of x except the rightmost 1-bit.if it's a power of 2, x & -x would equals x.
Code
class Solution { public boolean isPowerOfTwo(int n) { if (n == 0) return false; long x = (long) n; return (x & x - 1) == 0; } }