Перейти к содержимому

LeetCode 231 - Power of Two Java Solution | Easy O(1) Bit Manipulation

Bad Badshah

0:00 / 0:00

LeetCode 231 - Power of Two Java Solution | Easy O(1) Bit Manipulation

5 просмотров · 11 дн. назад
Bad Badshah
7 подписчиков
5 просмотров · 11 дн. назад
HELLO CODERS..... PROBLEM OVERVIEW: Given an integer n, return true if it is a power of two. Otherwise, return false. Can we solve it without loops or recursion in constant time? Yes, by using the binary properties of powers of two! THE CORE TRICK: Every power of two in binary contains exactly one bit set to 1 (for example, 8 is 1000, and 16 is 10000). When we subtract 1 from a power of two, all bits flip up to that set bit (for example, 7 is 0111). Applying a bitwise AND between n and (n - 1) will yield 0 if and only if n is a power of two! JAVA SOLUTION: public boolean isPowerOfTwo(int n) { return n is greater than 0 && (n & (n - 1)) == 0;} Got an alternative solution or a question? Drop it in the comments below! Hit LIKE if this visual walkthrough helped you master bit manipulation! #LeetCode #Java #CodingInterview #DataStructures #Algorithms #BitManipulation #LeetCode231 #SoftwareEngineering