Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created October 29, 2025 01:26
Show Gist options
  • Select an option

  • Save tatsuyax25/a0980fd21abe5e8da80dc5d164a1d63b to your computer and use it in GitHub Desktop.

Select an option

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
/**
* @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