commit 4d2f275db2683af3d8f8d82af5d5b8d2ecb805d3
parent 14bc4f624ae5c1068949840eb69893cb1ac80e19
Author: Jack Sangdahl <jack@pngu.org>
Date: Tue, 28 Oct 2025 18:41:38 -0600
3370. smallest number with all set bits
Diffstat:
2 files changed, 37 insertions(+), 0 deletions(-)
diff --git a/smallest_num_set_bits.c b/smallest_num_set_bits.c
@@ -0,0 +1,15 @@
+// 3370. Smallest Number With All Set Bits
+#include "leetcode.h"
+
+/*
+ * you are given a positive number 'n'. return the smallest number 'x' greater
+ * than or equal to 'n' such that the binary represeentation of 'x' contains
+ * only set bits.
+ */
+
+int smallestNumber(int n) { return INT_MAX >> __builtin_clz(n) - 1; }
+
+int main() {
+ printf("%d\n", smallestNumber(5)); // expect: 7
+ printf("%d\n", smallestNumber(10)); // expect: 15
+}
diff --git a/smallest_num_set_bits.py b/smallest_num_set_bits.py
@@ -0,0 +1,22 @@
+# 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 represeentation of 'x' contains
+only set bits.
+"""
+
+
+class Solution(object):
+ def smallestNumber(self, n):
+ """
+ :type n: int
+ :rtype: int
+ """
+ return (1 << n.bit_length()) - 1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.smallestNumber(n=5))
+ print(obj.smallestNumber(n=10))