Smallest Number With All Set Bits – Python Solution


class Solution:
    def smallestNumber(self, n: int) -> int:
        return (1 << n.bit_length()) - 1

Problem Description

So, you want to find the smallest number with all set bits? Imagine you’re at a party, and everyone is wearing a hat. You want to find the smallest hat size that fits everyone perfectly. In the world of numbers, "set bits" are like those party hats—if a bit is set, it’s like someone is wearing a hat. The challenge is to find the smallest number that has all its bits set to 1, given a number n that represents how many bits you want to set.

In simpler terms, if you want n bits to be set, you need to find the smallest number that can accommodate all those bits. Spoiler alert: it’s not as complicated as it sounds!

Approach

The code uses a bit manipulation technique to find the smallest number with all bits set. The expression (1 << n.bit_length()) - 1 shifts the number 1 to the left by the number of bits in n, effectively creating a number with all bits set to 1. It’s like flipping a switch on a light bulb—once you know how many bulbs (bits) you need, you just turn them all on!

Time and Space Complexity

Time Complexity: O(1) - The operation is constant time since it involves a few bit manipulations.

Space Complexity: O(1) - No additional space is used that scales with input size.

Real-World Example

Imagine you’re organizing a game night with your friends, and you need to set up a scoreboard. Each player gets a point for every game they win, and you want to display their scores in binary. If you have n players, you need a scoreboard that can show all their scores at once. The smallest number with all bits set will help you determine the maximum score you can display without running out of space on your scoreboard!

Similar Problems

2-Sum Solution in Python