[LeetCode] Smallest Number With All Set Bits

3370. Smallest Number With All Set Bits

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.

A set bit refers to a bit in the binary representation of a number that has a value of 1.

1
2
3
4
5
6
7
8
class Solution {
public:
int smallestNumber(int n) {
int res = 1;
while(res <= n) res *= 2;
return res - 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/01/PS/LeetCode/smallest-number-with-all-set-bits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.