Power of Two - The Coding Shala

Home >> Programming >> Power of Two

 In this post, we will learn how to check if the given number is Power of Two or not, and will implement its solution in Java.

Power of Two Problem

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 == 2^x.

Example 1:
Input: n = 1
Output: true
Explanation: 2^0 = 1

Example 2:
Input: n = 16
Output: true
Explanation: 2^4 = 16

Example 3:
Input: n = 3
Output: false

Power of Two Java Solution

Approach 1

Using Bit Manipulation.

Java Program: 

class Solution {
    public boolean isPowerOfTwo(int n) {
        if(n <= 0) return false;
        for(int i=0; i<32; i++) {
            if((n | (1<<i)) == (1 << i)) return true;
        return false;

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala