🚀 LeetCode Solution: Finding the Greatest Square and the Smallest Number
Here\u2019s how your LeetCode solution post could look:\n\n---\n\n### \uD83D\uDE80 LeetCode Solution: Finding the Greatest Square and the Smallest Number\n\n\uD
Here\u2019s how your LeetCode solution post could look:\n\n---\n\n### \uD83D\uDE80 LeetCode Solution: Finding the Greatest Square and the Smallest Number\n\n\uD83D\uDCA1 **Problem Statement**:  \nGiven a number `n`, the task is to:  \n1. Find the smallest number that is larger than `n` and is a power of 2.  \n2. Return the largest number smaller than this power of 2.\n\n---\n\n### \uD83E\uDDF5 **Code Explanation**\n\n```python\nclass Solution:\n    def greatestSquare(self, n):\n        # Convert number to its binary representation\n        cur = bin(n)[2:]  # Strips the \'0b\' prefix\n        # Create a binary number that\'s just one higher power of 2\n        greater = "1" + len(cur) * "0"\n        return int(greater, 2)  # Convert binary string back to integer\n\n    def smallestNumber(self, n: int) -> int:\n        # Find the nearest power of 2 that\'s greater than `n`\n        nearst = self.greatestSquare(n)\n        # Subtract 1 to find the largest number less than `nearst`\n        return nearst - 1\n```\n\n---\n\n### \uD83D\uDEE0\uFE0F **Step-by-Step Explanation**\n\n1. **Understanding the Function `greatestSquare`:**  \n   - Convert the number `n` to its binary representation using `bin(n)`.\n   - Skip the `"0b"` prefix using `[2:]`.\n   - Append a `"1"` followed by as many `"0"`s as the length of the binary number.\n   - Convert this binary string back to a decimal integer to find the nearest power of 2.\n\n   \uD83D\uDCDD *Example*:  \n   For `n = 5` (binary: `101`):  \n   - Append `"1"` to create `1000`.  \n   - This corresponds to `8` in decimal.\n\n2. **Understanding the Function `smallestNumber`:**  \n   - Use `greatestSquare` to find the next power of 2 greater than `n`.\n   - Subtract `1` from this number to get the largest number less than that power of 2.\n\n   \uD83D\uDCDD *Example*:  \n   For `n = 5`:  \n   - Nearest power of 2 = `8`.  \n   - Subtract `1` \u2192 Result = `7`.\n\n---\n\n### \uD83C\uDF1F **Examples**\n\n#### \uD83D\uDD0D Input: `n = 5`  \n- **Step 1:** Binary of 5 is `101`.  \n- **Step 2:** Append `"1"` + `"0"` * 3 \u2192 Nearest power of 2 = `8`.  \n- **Step 3:** Subtract `1` \u2192 Result = `7`.\n\n#### \uD83D\uDD0D Input: `n = 12`  \n- **Step 1:** Binary of 12 is `1100`.  \n- **Step 2:** Append `"1"` + `"0"` * 4 \u2192 Nearest power of 2 = `16`.  \n- **Step 3:** Subtract `1` \u2192 Result = `15`.\n\n---\n\n### \u26A1 Key Points:\n- This solution works in **O(log(n))**, where `log(n)` comes from binary conversion.\n- Efficient for handling large numbers due to its simplicity in bit manipulation.\n\nHope this helps! \uD83C\uDF1F Keep coding and solving! \uD83D\uDCBB
['Python', 'Python3']