Posts Power of 2 (geeksforgeeks - SDE Sheet)
Post
Cancel

Power of 2 (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given a non-negative integer n. The task is to check if it is a power of 2.

geeksforgeeks

SOLUTION

The number of set bits should be 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {

    public static boolean isPowerofTwo(long n) {

        int c = 0;

        while( n != 0 ){

            if( (n&1) != 0 ){
                c++;
            }

            n = n >> 1;

            if(c > 1)
                return false;

        }

        return c == 1;

    }

}
This post is licensed under CC BY 4.0 by the author.