Count Monobit Integers Problem
#3827
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3827.
You are given an integer n.
An integer is called Monobit if all bits in its binary representation are the same.
Return the count of Monobit integers in the range [0, n] (inclusive).
Example 1:
Input: n = 1
Output: 2
Explanation:
- The integers in the range [0, 1] have binary representations "0" and "1".
- Each representation consists of identical bits. Thus, the answer is 2.
Example 2:
Input: n = 4
Output: 3
Explanation:
- The integers in the range [0, 4] include binaries "0", "1", "10", "11", and "100".
- Only 0, 1 and 3 satisfy the Monobit condition. Thus, the answer is 3.
Constraints:
0 <= n <= 1000
Solution
Approach: Simulation
A Monobit integer is either 0 or a number whose binary form is all ones (1, 3, 7, 15, ...). Start the count at 1 for the number 0, then generate the all-ones numbers in increasing order (each is the previous one plus the next power of two) and count them while they do not exceed n.
Complexity: O(log n) time and O(1) space.
class Solution:
def countMonobit(self, n: int) -> int:
ans = x = 1
i = 1
while x <= n:
ans += 1
x += 1 << i
i += 1
return ans