↓快轉到主要內容
  1. LeetCode/

LeetCode 3827: Count Monobit Integers

·1 分鐘· ·
LeetCode Easy Bit-Manipulation Enumeration
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2026-02-01

  • 提交紀錄:Accepted(一次通過)

解題思路
#

二進位每一位都一樣:全部是 0 的只有 0,全部是 1 的是 1, 3, 7, 15, ... 也就是 2^k - 1(Bit Manipulation 模板三)。2^k - 1 <= n 等於 2^k <= n + 1,k 從 1 數到 (n + 1).bit_length() - 1,再加上 0,總共 (n + 1).bit_length() 個。

我的解法
#

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

我當時用迴圈從 1 開始一直加 2^power,產生 1、3、7…,數有幾個 <= n,再加上 0;結果一樣。

複雜度
#

時間 O(1),空間 O(1)。

要特別避免的錯誤
#

  • 別忘了 0 也算。

面試口說整理
#

每一位都一樣的數只有 0 和 2^k - 1。2^k - 1 <= n 的 k 有 (n + 1).bit_length() - 1 個,加上 0 就是答案。時間 O(1)。

相關文章

LeetCode 1763: Longest Nice Substring
·1 分鐘
LeetCode Easy Sliding-Window Divide-and-Conquer Hash-Table String Bit-Manipulation
LeetCode 1763 解題筆記:沒有大小寫配對的字元一定不在答案裡,用它切開字串遞迴;長度相同時取左邊的
LeetCode 3750: Minimum Number of Flips to Reverse Binary String
·1 分鐘
LeetCode Easy Two-Pointers Bit-Manipulation String
LeetCode 3750 解題筆記:把二進位字串跟它的反轉逐位比較,不同的位數就是答案
LeetCode 3688: Bitwise OR of Even Numbers in an Array
·1 分鐘
LeetCode Easy Bit-Manipulation Array Simulation
LeetCode 3688 解題筆記:只對偶數做 OR;初始值 0 剛好也是「沒有偶數」時的答案
LeetCode 2859: Sum of Values at Indices With K Set Bits
·1 分鐘
LeetCode Easy Array Bit-Manipulation
LeetCode 2859 解題筆記:看的是 index 的二進位有幾個 1,不是值
LeetCode 762: Prime Number of Set Bits in Binary Representation
·1 分鐘
LeetCode Easy Math Bit-Manipulation Primality-Test
LeetCode 762 解題筆記:數字最多 10^6 < 2^20,1 的個數最多 19,直接比對小質數集合
LeetCode 461: Hamming Distance
·1 分鐘
LeetCode Easy Bit-Manipulation
LeetCode 461 解題筆記:x ^ y 的每個 1 就是一個不同的位元,數 1 的個數