Table of Contents
Problem statement
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
.
Power of 2
Why (n&(nā1))=0 correct ?
- If n is a power of two, it has exactly one bit set.
- Subtracting 1 from šn flips all the bits after the set bit, including the set bit itself.
- Performing a bitwise AND between n and nā1 results in zero, because the single set bit in n aligns with a 0 in nā1, and all other bits in n are already zero.
How to use Bitwise Operator ?
Operator | Description | Java | C++. | Python3 | Golang | Result | Explanation |
& | Bitwise AND | 4 & 3 | 4 &3 | 4 & 3 | 4 & 3 | 0 | 4 & 3 = 0 (Binary: 100 & 011 = 000) |
| | Bitwise OR | 4 | 3 | 4 | 3 | 4 | 3 | 4 | 3 | 7 | 4 | 3 = 7 (Binary: 100 | 011 = 111) |
^ | Bitwise XOR | 4 ^ 3 | 4^3 | 4 ^ 3 | 4 ^ 3 | 7 | 4 ^ 3 = 7 (Binary: 100 ^ 011 = 111) |
~ | Bitwise NOT (Unary) | ~4 | ~4 | ~4 | ^4 | -5 | ~4 = -5 (Binary: ~100 = 1111 1011) |
<< | Left shift | 4<<3 | 4<<3 | 4 << 3 | 4 << 3 | 32 | 4 << 3 = 32 (Binary: 100 << 3 = 100000) |
>> | Right shift | 4 >> 3 | 4 >> 3 | 4 >> 3 | 4 >> 3 | 0 | 4 >> 3 = 0 (Binary: 100 >> 3 = 0) |
Examples
Let’s apply the examples using ( n = 8 ) and ( n-1 = 7 ):
Bitwise AND (`&`):
( 8 & 7 ) evaluates to ( 00001000 & 00000111 = 00000000 ).
Bitwise OR (`|`):
( 8 | 7 ) evaluates to ( 00001000 | 00000111 = 00001111 ).
Bitwise XOR (`^`):
( 8 ^ 7 ) evaluates to ( 00001000 ^ 00000111 = 00001111 ).
Bitwise NOT (`~`):
( ~ 8 ) (Unary NOT) evaluates to ( 11110111 ).
Left Shift (`<<`):
( 8 << 1 ) (Left shift by 1) evaluates to ( 00001000 << 1 = 00010000 ).
Right Shift (`>>`):
( 8 >> 1 ) (Right shift by 1) evaluates to ( 00001000 >> 1 = 00000100 ).
JAVA CODE
class Solution {
public boolean isPowerOfTwo(int n) {
if ((n == 0) || (n<0)){
return false;
}
return (0 == (n & (n-1)));
}
}
How to use logical operator ?
Operator | Description | Go Syntax | Java Syntax | C++ Syntax | Python 3 Syntax |
&& | Logical AND | a && b | a && b | a && b | a and b |
|| | Logical OR | a || b | a || b | a || b | a or b |
! | Logical NOT | !a | !a | !a | not a |
==’ | Equal to | a == b | a == b | a == b | a == b |
!= | Not equal to | a != b | a != b | a != b | a != b |
> | Greater than | a > b | a > b | a > b | a > b |
< | Less than | a < b | a < b | a < b | a < b |
>= | Greater than or equal | a >= b | a >= b | a >= b | a >= b |
<= | Less than or equal | a <= b | a <= b | a <= b | a <= b |
Visit Previous Problem#1
Leave a Reply