↓Skip to main content
  1. LeetCode/

LeetCode 3827: Count Monobit Integers

·1 min· ·
LeetCode Easy Bit-Manipulation Enumeration
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2026-02-01

  • Submissions: Accepted (first try)

Approach
#

All bits equal: all zeros is only 0, and all ones is 1, 3, 7, 15, ..., i.e. 2^k - 1 (Bit Manipulation Template 3). 2^k - 1 <= n means 2^k <= n + 1, so k runs from 1 to (n + 1).bit_length() - 1; adding 0 gives (n + 1).bit_length() in total.

My Solution
#

class Solution:
    def countMonobit(self, n: int) -> int:
        return (n + 1).bit_length()

I originally looped, adding 2^power starting from 1 to generate 1, 3, 7, …, counting those <= n plus 0; same result.

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • Do not forget that 0 counts.

Interview Explanation
#

Numbers with all-equal bits are just 0 and 2^k - 1. There are (n + 1).bit_length() - 1 values of k with 2^k - 1 <= n, plus 0. Time O(1).

Related

LeetCode 1763: Longest Nice Substring
·2 mins
LeetCode Easy Sliding-Window Divide-and-Conquer Hash-Table String Bit-Manipulation
LeetCode 1763 note: a character whose other case never appears cannot be in the answer, so split on it and recurse, preferring the left side on ties
LeetCode 3750: Minimum Number of Flips to Reverse Binary String
·2 mins
LeetCode Easy Two-Pointers Bit-Manipulation String
LeetCode 3750 note: compare the binary string with its reverse bit by bit; the number of mismatches is the answer
LeetCode 3688: Bitwise OR of Even Numbers in an Array
·1 min
LeetCode Easy Bit-Manipulation Array Simulation
LeetCode 3688 note: OR only the even numbers; the starting value 0 is also the answer when there are none
LeetCode 2859: Sum of Values at Indices With K Set Bits
·1 min
LeetCode Easy Array Bit-Manipulation
LeetCode 2859 note: count the set bits of the index, not of the value
LeetCode 762: Prime Number of Set Bits in Binary Representation
·1 min
LeetCode Easy Math Bit-Manipulation Primality-Test
LeetCode 762 note: numbers are below 10^6 < 2^20, so the set-bit count is at most 19; check it against a small set of primes
LeetCode 461: Hamming Distance
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 461 note: each 1 in x ^ y is a differing bit, so count the ones