Watch 8 video solutions for Count Monobit Integers, a easy level problem involving Bit Manipulation, Enumeration. This walkthrough by Developer Coder has 356 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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:
[0, 1] have binary representations "0" and "1".Example 2:
Input: n = 4
Output: 3
Explanation:
[0, 4] include binaries "0", "1", "10", "11", and "100".
Constraints:
0 <= n <= 1000Problem Overview: Count how many integers in the given range are monobit. A monobit integer has exactly one set bit (1) in its binary representation. In other words, its binary form looks like 1, 10, 100, 1000, etc.
Approach 1: Simulation with Bit Check (O(n) time, O(1) space)
The straightforward approach is to iterate through every integer in the range and check whether it contains exactly one set bit. A number has a single set bit if the expression x & (x - 1) equals zero while x > 0. This works because subtracting 1 flips the lowest set bit and all bits to its right, so the bitwise AND removes that bit entirely for powers of two.
During the scan, perform this constant‑time check for each number and increment a counter whenever the condition holds. This technique relies on a classic Bit Manipulation trick that quickly detects whether a number is a power of two. Since each integer is processed once, the runtime is linear with respect to the size of the range.
This method is simple, readable, and efficient for the typical constraints of an easy problem. The logic involves basic Enumeration: iterate through candidates and validate them using a constant‑time property of their binary form.
Why the bit trick works: Numbers with exactly one set bit are powers of two. Their binary representation contains a single 1. When you compute x & (x - 1), that single bit disappears, producing zero. Any number with multiple set bits leaves at least one bit after the operation.
Recommended for interviews: The simulation approach using x & (x - 1) is what interviewers typically expect. It shows familiarity with core bit manipulation patterns. A brute-force method that counts bits using loops also works, but the bit trick demonstrates stronger understanding and runs with the same O(n) time while keeping the code concise.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Bit Count per Number | O(n log n) | O(1) | Simple brute force when checking bits by shifting or built-in popcount |
| Bit Trick: x & (x - 1) | O(n) | O(1) | Best general solution; constant-time monobit check using bit manipulation |