#3827

Count Monobit Integers

Easy
Bit ManipulationEnumerationBit ManipulationMathematical Patterns
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Monobit integers are either 0 or powers of 2 minus 1. We can efficiently count these by recognizing the pattern.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a count to 0.
  2. 2Step 2: Count 0 as a Monobit integer.
  3. 3Step 3: For each power of 2 (1, 3, 7, ...), check if it's less than or equal to n and increment the count.
solution.py7 lines
1def countMonobitIntegers(n):
2    count = 1  # for 0
3    power = 1
4    while power <= n:
5        count += 1
6        power = (power << 1) | 1
7    return count

Complexity note: The loop runs logarithmically with respect to n, as we double the power each iteration.

  • 1Monobit integers are 0 and numbers of the form 2^k - 1.
  • 2Recognizing patterns in binary helps simplify counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.