Created
October 29, 2025 01:26
-
-
Save tatsuyax25/a0980fd21abe5e8da80dc5d164a1d63b to your computer and use it in GitHub Desktop.
You are given a positive number n. Return the smallest number x greater than or equal to n, such that the binary representation of x contains only set bits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number} n | |
| * @return {number} | |
| */ | |
| var smallestNumber = function(n) { | |
| // Start with 1 and keep shifting left and OR-ing to build numbers like 1, 3, 7, 15, 31, etc. | |
| let x = 1; | |
| // Keep generating numbers with all bits set until we find one >= n | |
| while (x < n) { | |
| // Shift left by 1 (multiply by 2) and add 1 to set the next bit | |
| x = (x << 1) | 1; | |
| } | |
| return x; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment