Skip to main content
Back to problems
#3827
Easy Algorithms

Count monobit integers

Bit Manipulation Enumeration
66.1% acceptance
Mar 16, 2026
53
1
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).

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_monobit(n: i32) -> i32 {
    let mut count = 0;
    for i in 0..=n {
      if i == 0 {
        count += 1;
      } else if i & (i + 1) == 0 {
        // All bits are 1: numbers like 1, 3, 7, 15, 31, ...
        count += 1;
      }
    }
    count
  }
}