Power of Two - The Coding Shala
Home >> Programming >> Power of Two
Other Posts You May Like
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; } }
- LeetCode - Single Number
- LeetCode - Single Number 2
- Reverse Bits
- LeetCode - Blub Switcher
- Simple XML Validator
Comments
Post a Comment