Issue
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
.
Constraints
Follow up
Could you solve it without loops/recursion?
- Solution
Bit manipulation
Solutions
Most voted
Recrusion
Iteration
https://leetcode.com/problems/power-of-two/discuss/2403463/Javascript-Solution
Bit manipulation
https://leetcode.com/problems/power-of-two/discuss/369024/100-fastest-0ms-one-line-solution-with-explanation-binary-trick


Everyone's
東
Hao
YC
Becky
月薪
Discussion
Bit manipulation
Negative binary representation system
Link
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
How to represent number with the same absolute value but different sign?
Sign Magnitude
- Use the Most Significant Bit (MSB), the leftmost bit in a number, to represent the sign.
- Only 7 bits remain for magnitude.
- Normally an 8 bit value would have the range of 0 to 255. The range of a signed 8 bit number is now -127 to 127 because the
value of magnitude
here (0000001) is still the same, which could cause error when we adding and subtracting values.
One's Complement
- When representing negative numbers, you invert all the bits. The 1's become 0's and the 0's become 1's.
- Because the range of the system is -127 to 127, it has the same issue which Sign Magnitude system faces.
Two's Complement
- Two's complement is much more widely used, including Javascript, than one's complement.
- Like One's Complement, We first invert the bits, but the different things here is that we would then add one.
Example to find negative two's complement numbers
Steps
- Find the positive binary value for the negative number you want to represent.
- Add a 0 to the front of the number, to indicate that it is positive.
- Invert or find the complement of each bit in the number.
- Add 1 to this number.
Let's find -1
- Signed two's complement number has a range of -128 to 127. Unlike one's complement and sign magnitude, two's complement does not have addition and subtraction problems.
Bitwise Operations
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →