Power of 2

Leetcode Problem #231

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 ?

OperatorDescriptionJavaC++. Python3GolangResultExplanation
&Bitwise AND4 & 34 &34 & 34 & 304 & 3 = 0 (Binary: 100 & 011 = 000)
|Bitwise OR4 | 34 | 34 | 34 | 374 | 3 = 7 (Binary: 100 | 011 = 111)
^Bitwise XOR4 ^ 34^34 ^ 34 ^ 374 ^ 3 = 7 (Binary: 100 ^ 011 = 111)
~Bitwise NOT (Unary)~4~4~4^4 -5~4 = -5 (Binary: ~100 = 1111 1011)
<<Left shift4<<34<<34 << 34 << 3324 << 3 = 32 (Binary: 100 << 3 = 100000)
>>Right shift4 >> 34 >> 34 >> 34 >> 304 >> 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 ?

OperatorDescriptionGo SyntaxJava SyntaxC++ SyntaxPython 3 Syntax
&&Logical ANDa && ba && ba && ba and b
||Logical ORa || ba || ba || ba or b
!Logical NOT!a!a!anot a
==’Equal toa == ba == ba == ba == b
!=Not equal toa != ba != ba != ba != b
>Greater thana > ba > ba > ba > b
<Less thana < ba < ba < ba < b
>=Greater than or equala >= ba >= ba >= ba >= b
<=Less than or equala <= ba <= ba <= ba <= b
Logical operator

Visit Previous Problem#1

Similar Questions

One response to “Power of 2”

  1. […] Solve next problem #2 […]

Leave a Reply

Your email address will not be published. Required fields are marked *