How to check if a number is a power of two in Java

🔹 Day 51: Power of Two (LeetCode #231) 📌 Problem Statement: 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. ✅ My Approach: I checked whether the number can be continuously divided by 2 until it reaches 1: If n is less than or equal to 0, it’s not a power of two. While n is divisible by 2, divide it by 2. If the result equals 1, then it’s a power of two; otherwise, it’s not. 📊 Complexity: Time Complexity: O(log n) — each division by 2 reduces n exponentially. Space Complexity: O(1) ⚡ Submission Stats: Runtime: 1 ms (Beats 33.54%) Memory: 41.04 MB (Beats 41.60%) 💡 Reflection: This problem strengthened my understanding of how powers of two follow a binary pattern. It also reminded me that bit manipulation (n > 0 && (n & (n-1)) == 0) can offer an even faster alternative. ⚡ #LeetCode #Java #Math #BitManipulation #100DaysOfCode #Day51

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories