Skip to content
Programming101
Programmingoneonone

Learn everything about programming

  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programmingoneonone

Learn everything about programming

Leetcode Power of Two problem solution

YASH PAL, 31 July 2024

In this Leetcode Power of Two problem solution, you are 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.

Leetcode Power of Two problem solution

Problem solution in Python.

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n <= 0:
            return False
        if n == 1:
            return True
        
        while n > 1:
            n /= 2
        return n == 1

Problem solution in Java.

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n <= 0){
            return false;
        }
        else if ((n & (n - 1)) == 0){
            return true;
        }
        else {
            return false;
        }
    }
}

Problem solution in C++.

class Solution {
public:
    bool isPowerOfTwo(int n) {
        bool a;
        if(n==0){a=false;}        
        else if(n==1){a=true;}        
        else{
            if(ceil(log2(n)) == floor(log2(n))){a=true;}
            else{a=false;}
        }return a;
    }
};

Problem solution in C.

bool isPowerOfTwo(int n){
    long int x = n;
    if(n && !(n & (x-1))) return true;
    else return false;
}

coding problems solutions

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes