3370. Smallest Number With All Set Bits #2355
-
|
Topics: You are given a positive number Return the smallest number Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find the smallest number ≥ n that has all 1s in its binary representation. The key insight is that numbers with all set bits are of the form Here's my approach:
Let's implement this solution in PHP: 3370. Smallest Number With All Set Bits <?php
/**
* @param Integer $n
* @return Integer
*/
function smallestNumber($n) {
// If n is already all 1s, return it
if (($n & ($n + 1)) == 0) {
return $n;
}
// Find the bit length of n
$bitLength = 0;
$temp = $n;
while ($temp > 0) {
$bitLength++;
$temp >>= 1;
}
// Return the next number with all bits set
return (1 << $bitLength) - 1;
}
// Test cases
echo smallestNumber(5) . PHP_EOL; // Output: 7
echo smallestNumber(10) . PHP_EOL; // Output: 15
echo smallestNumber(3) . PHP_EOL; // Output: 3
?>Explanation:
Let's test with the examples:
The time complexity is O(log n) and space complexity is O(1). |
Beta Was this translation helpful? Give feedback.
We need to find the smallest number ≥ n that has all 1s in its binary representation.
The key insight is that numbers with all set bits are of the form
2^k - 1(like 1, 3, 7, 15, 31, etc.). So I need to find the smallest number of this form that is ≥ n.Here's my approach:
(1 << k) - 1where k is the bit lengthLet's implement this solution in PHP: 3370. Smallest Number With All Set Bits