普通视图

发现新文章,点击刷新页面。
昨天 — 2026年2月22日LeetCode 每日一题题解

计算尾零个数(Python/Java/C++/Go/C/JS/Rust)

作者 endlesscheng
2026年2月22日 07:15

以 $n = 1010010$ 为例。从右往左,我们需要计算 $1001$ 的间距 $3$,以及 $101$ 的间距 $2$:

  1. 去掉 $n$ 末尾的 $10$,得到 $10100$。这一步可以先计算出 $n$ 的 $\text{lowbit} = 10$,然后把 $n$ 更新成 $\dfrac{n}{2\cdot \text{lowbit}}$。$\text{lowbit}$ 的原理请看 从集合论到位运算,常见位运算技巧分类总结
  2. 计算 $10100$ 的尾零个数加一,得到 $3$,即 $1001$ 的间距。然后把 $10100$ 右移 $3$ 位,得到 $10$。
  3. 计算 $10$ 的尾零个数加一,得到 $2$,即 $101$ 的间距。然后把 $101$ 右移 $2$ 位,得到 $0$。算法结束。
class Solution:
    def binaryGap(self, n: int) -> int:
        ans = 0
        n //= (n & -n) * 2  # 去掉 n 末尾的 100..0
        while n > 0:
            gap = (n & -n).bit_length()  # n 的尾零个数加一
            ans = max(ans, gap)
            n >>= gap  # 去掉 n 末尾的 100..0
        return ans
class Solution {
    public int binaryGap(int n) {
        int ans = 0;
        n /= (n & -n) * 2; // 去掉 n 末尾的 100..0
        while (n > 0) {
            int gap = Integer.numberOfTrailingZeros(n) + 1;
            ans = Math.max(ans, gap);
            n >>= gap; // 去掉 n 末尾的 100..0
        }
        return ans;
    }
}
class Solution {
public:
    int binaryGap(int n) {
        int ans = 0;
        n /= (n & -n) * 2; // 去掉 n 末尾的 100..0
        while (n > 0) {
            int gap = countr_zero((uint32_t) n) + 1;
            ans = max(ans, gap);
            n >>= gap; // 去掉 n 末尾的 100..0
        }
        return ans;
    }
};
#define MAX(a, b) ((b) > (a) ? (b) : (a))

int binaryGap(int n) {
    int ans = 0;
    n /= (n & -n) * 2; // 去掉 n 末尾的 100..0
    while (n > 0) {
        int gap = __builtin_ctz(n) + 1;
        ans = MAX(ans, gap);
        n >>= gap; // 去掉 n 末尾的 100..0
    }
    return ans;
}
func binaryGap(n int) (ans int) {
n /= n & -n * 2 // 去掉 n 末尾的 100..0
for n > 0 {
gap := bits.TrailingZeros(uint(n)) + 1
ans = max(ans, gap)
n >>= gap // 去掉 n 末尾的 100..0
}
return
}
var binaryGap = function(n) {
    let ans = 0;
    n /= (n & -n) * 2; // 去掉 n 末尾的 100..0
    while (n > 0) {
        const gap = 32 - Math.clz32(n & -n); // n 的尾零个数加一
        ans = Math.max(ans, gap);
        n >>= gap; // 去掉 n 末尾的 100..0
    }
    return ans;
};
impl Solution {
    pub fn binary_gap(mut n: i32) -> i32 {
        let mut ans = 0;
        n /= (n & -n) * 2; // 去掉 n 末尾的 100..0
        while n > 0 {
            let gap = n.trailing_zeros() + 1;
            ans = ans.max(gap);
            n >>= gap; // 去掉 n 末尾的 100..0
        }
        ans as _
    }
}

复杂度分析

  • 时间复杂度:$\mathcal{O}(k)$,其中 $k$ 是 $n$ 二进制中的 $1$ 的个数。
  • 空间复杂度:$\mathcal{O}(1)$。

专题训练

见下面位运算题单的「一、基础题」。

分类题单

如何科学刷题?

  1. 滑动窗口与双指针(定长/不定长/单序列/双序列/三指针/分组循环)
  2. 二分算法(二分答案/最小化最大值/最大化最小值/第K小)
  3. 单调栈(基础/矩形面积/贡献法/最小字典序)
  4. 网格图(DFS/BFS/综合应用)
  5. 位运算(基础/性质/拆位/试填/恒等式/思维)
  6. 图论算法(DFS/BFS/拓扑排序/基环树/最短路/最小生成树/网络流)
  7. 动态规划(入门/背包/划分/状态机/区间/状压/数位/数据结构优化/树形/博弈/概率期望)
  8. 常用数据结构(前缀和/差分/栈/队列/堆/字典树/并查集/树状数组/线段树)
  9. 数学算法(数论/组合/概率期望/博弈/计算几何/随机算法)
  10. 贪心与思维(基本贪心策略/反悔/区间/字典序/数学/思维/脑筋急转弯/构造)
  11. 链表、树与回溯(前后指针/快慢指针/DFS/BFS/直径/LCA)
  12. 字符串(KMP/Z函数/Manacher/字符串哈希/AC自动机/后缀数组/子序列自动机)

我的题解精选(已分类)

欢迎关注 B站@灵茶山艾府

每日一题-二进制间距🟢

2026年2月22日 00:00

给定一个正整数 n,找到并返回 n 的二进制表示中两个 相邻 1 之间的 最长距离 。如果不存在两个相邻的 1,返回 0

如果只有 0 将两个 1 分隔开(可能不存在 0 ),则认为这两个 1 彼此 相邻 。两个 1 之间的距离是它们的二进制表示中位置的绝对差。例如,"1001" 中的两个 1 的距离为 3 。

 

    示例 1:

    输入:n = 22
    输出:2
    解释:22 的二进制是 "10110" 。
    在 22 的二进制表示中,有三个 1,组成两对相邻的 1 。
    第一对相邻的 1 中,两个 1 之间的距离为 2 。
    第二对相邻的 1 中,两个 1 之间的距离为 1 。
    答案取两个距离之中最大的,也就是 2 。
    

    示例 2:

    输入:n = 8
    输出:0
    解释:8 的二进制是 "1000" 。
    在 8 的二进制表示中没有相邻的两个 1,所以返回 0 。
    

    示例 3:

    输入:n = 5
    输出:2
    解释:5 的二进制是 "101" 。
    

     

    提示:

    • 1 <= n <= 109

    【宫水三叶】简单模拟题

    作者 AC_OIer
    2022年4月24日 08:45

    模拟

    根据题意进行模拟即可,遍历 $n$ 的二进制中的每一位 $i$,同时记录上一位 $1$ 的位置 $j$,即可得到所有相邻 $1$ 的间距,所有间距取 $\max$ 即是答案。

    代码:

    ###Java

    class Solution {
        public int binaryGap(int n) {
            int ans = 0;
            for (int i = 31, j = -1; i >= 0; i--) {
                if (((n >> i) & 1) == 1) {
                    if (j != -1) ans = Math.max(ans, j - i);
                    j = i;
                }
            }
            return ans;
        }
    }
    
    • 时间复杂度:$O(\log{n})$
    • 空间复杂度:$O(1)$

    加餐 & 加练

    今日份加餐:【面试高频题】难度 1.5/5,脑筋急转弯类模拟题 🎉🎉🎉

    或是考虑加练如下「模拟」题 🍭🍭🍭

    题目 题解 难度 推荐指数
    6. Z 字形变换 LeetCode 题解链接 中等 🤩🤩🤩
    8. 字符串转换整数 (atoi) LeetCode 题解链接 中等 🤩🤩🤩
    12. 整数转罗马数字 LeetCode 题解链接 中等 🤩🤩
    59. 螺旋矩阵 II LeetCode 题解链接 中等 🤩🤩🤩🤩
    65. 有效数字 LeetCode 题解链接 困难 🤩🤩🤩
    73. 矩阵置零 LeetCode 题解链接 中等 🤩🤩🤩🤩
    89. 格雷编码 LeetCode 题解链接 中等 🤩🤩🤩🤩
    166. 分数到小数 LeetCode 题解链接 中等 🤩🤩🤩🤩
    260. 只出现一次的数字 III LeetCode 题解链接 中等 🤩🤩🤩🤩
    414. 第三大的数 LeetCode 题解链接 中等 🤩🤩🤩🤩
    419. 甲板上的战舰 LeetCode 题解链接 中等 🤩🤩🤩🤩
    443. 压缩字符串 LeetCode 题解链接 中等 🤩🤩🤩🤩
    457. 环形数组是否存在循环 LeetCode 题解链接 中等 🤩🤩🤩🤩
    528. 按权重随机选择 LeetCode 题解链接 中等 🤩🤩🤩🤩
    539. 最小时间差 LeetCode 题解链接 中等 🤩🤩🤩🤩
    726. 原子的数量 LeetCode 题解链接 困难 🤩🤩🤩🤩

    注:以上目录整理来自 wiki,任何形式的转载引用请保留出处。


    最后

    如果有帮助到你,请给题解点个赞和收藏,让更多的人看到 ~ ("▔□▔)/

    也欢迎你 关注我 和 加入我们的「组队打卡」小群 ,提供写「证明」&「思路」的高质量题解。

    所有题解已经加入 刷题指南,欢迎 star 哦 ~

    二进制间距

    2022年4月22日 22:07

    方法一:位运算

    思路与算法

    我们可以使用一个循环从 $n$ 二进制表示的低位开始进行遍历,并找出所有的 $1$。我们用一个变量 $\textit{last}$ 记录上一个找到的 $1$ 的位置。如果当前在第 $i$ 位找到了 $1$,那么就用 $i - \textit{last}$ 更新答案,再将 $\textit{last}$ 更新为 $i$ 即可。

    在循环的每一步中,我们可以使用位运算 $\texttt{n & 1}$ 获取 $n$ 的最低位,判断其是否为 $1$。在这之后,我们将 $n$ 右移一位:$\texttt{n = n >> 1}$,这样在第 $i$ 步时,$\texttt{n & 1}$ 得到的就是初始 $n$ 的第 $i$ 个二进制位。

    代码

    ###Python

    class Solution:
        def binaryGap(self, n: int) -> int:
            last, ans, i = -1, 0, 0
            while n:
                if n & 1:
                    if last != -1:
                        ans = max(ans, i - last)
                    last = i
                n >>= 1
                i += 1
            return ans
    

    ###C++

    class Solution {
    public:
        int binaryGap(int n) {
            int last = -1, ans = 0;
            for (int i = 0; n; ++i) {
                if (n & 1) {
                    if (last != -1) {
                        ans = max(ans, i - last);
                    }
                    last = i;
                }
                n >>= 1;
            }
            return ans;
        }
    };
    

    ###Java

    class Solution {
        public int binaryGap(int n) {
            int last = -1, ans = 0;
            for (int i = 0; n != 0; ++i) {
                if ((n & 1) == 1) {
                    if (last != -1) {
                        ans = Math.max(ans, i - last);
                    }
                    last = i;
                }
                n >>= 1;
            }
            return ans;
        }
    }
    

    ###C#

    public class Solution {
        public int BinaryGap(int n) {
            int last = -1, ans = 0;
            for (int i = 0; n != 0; ++i) {
                if ((n & 1) == 1) {
                    if (last != -1) {
                        ans = Math.Max(ans, i - last);
                    }
                    last = i;
                }
                n >>= 1;
            }
            return ans;
        }
    }
    

    ###C

    #define MAX(a, b) ((a) > (b) ? (a) : (b))
    
    int binaryGap(int n) {
        int last = -1, ans = 0;
        for (int i = 0; n; ++i) {
            if (n & 1) {
                if (last != -1) {
                    ans = MAX(ans, i - last);
                }
                last = i;
            }
            n >>= 1;
        }
        return ans;
    }
    

    ###go

    func binaryGap(n int) (ans int) {
        for i, last := 0, -1; n > 0; i++ {
            if n&1 == 1 {
                if last != -1 {
                    ans = max(ans, i-last)
                }
                last = i
            }
            n >>= 1
        }
        return
    }
    
    func max(a, b int) int {
        if b > a {
            return b
        }
        return a
    }
    

    ###JavaScript

    var binaryGap = function(n) {
        let last = -1, ans = 0;
        for (let i = 0; n != 0; ++i) {
            if ((n & 1) === 1) {
                if (last !== -1) {
                    ans = Math.max(ans, i - last);
                }
                last = i;
            }
            n >>= 1;
        }
        return ans;
    };
    

    复杂度分析

    • 时间复杂度:$O(\log n)$。循环中的每一步 $n$ 会减少一半,因此需要 $O(\log n)$ 次循环。

    • 空间复杂度:$O(1)$。

    昨天以前LeetCode 每日一题题解

    三种方法:暴力枚举 / 数位 DP / 组合数学(Python/Java/C++/Go)

    作者 endlesscheng
    2026年2月21日 08:25

    方法一:暴力枚举

    枚举 $[\textit{left},\textit{right}]$ 中的整数 $x$,计算 $x$ 二进制中的 $1$ 的个数 $c$。如果 $c$ 是质数,那么答案增加一。

    由于 $[1,10^6]$ 中的二进制数至多有 $19$ 个 $1$,所以只需 $19$ 以内的质数,即

    $$
    2, 3, 5, 7, 11, 13, 17, 19
    $$

    primes = {2, 3, 5, 7, 11, 13, 17, 19}
    
    class Solution:
        def countPrimeSetBits(self, left: int, right: int) -> int:
            ans = 0
            for x in range(left, right + 1):
                if x.bit_count() in primes:
                    ans += 1
            return ans
    
    class Solution {
        private static final Set<Integer> primes = Set.of(2, 3, 5, 7, 11, 13, 17, 19);
    
        public int countPrimeSetBits(int left, int right) {
            int ans = 0;
            for (int x = left; x <= right; x++) {
                if (primes.contains(Integer.bitCount(x))) {
                    ans++;
                }
            }
            return ans;
        }
    }
    
    class Solution {
        // 注:也可以用哈希集合做,由于本题质数很少,用数组也可以
        static constexpr int primes[] = {2, 3, 5, 7, 11, 13, 17, 19};
    
    public:
        int countPrimeSetBits(int left, int right) {
            int ans = 0;
            for (uint32_t x = left; x <= right; x++) {
                if (ranges::contains(primes, popcount(x))) {
                    ans++;
                }
            }
            return ans;
        }
    };
    
    // 注:也可以用哈希集合做,由于本题质数很少,用 slice 也可以
    var primes = []int{2, 3, 5, 7, 11, 13, 17, 19}
    
    func countPrimeSetBits(left, right int) (ans int) {
    for x := left; x <= right; x++ {
    if slices.Contains(primes, bits.OnesCount(uint(x))) {
    ans++
    }
    }
    return
    }
    

    复杂度分析

    • 时间复杂度:$\mathcal{O}(\textit{right}-\textit{left})$。
    • 空间复杂度:$\mathcal{O}(1)$。不计入质数集合的空间。

    方法二:上下界数位 DP

    数位 DP v1.0 模板讲解

    数位 DP v2.0 模板讲解(上下界数位 DP)

    对于本题,在递归边界($i=n$)我们需要判断是否填了质数个 $1$,所以需要参数 $\textit{cnt}_1$ 表示填过的 $1$ 的个数。其余同 v2.0 模板。

    primes = {2, 3, 5, 7, 11, 13, 17, 19}
    
    class Solution:
        def countPrimeSetBits(self, left: int, right: int) -> int:
            high_s = list(map(int, bin(right)[2:]))  # 避免在 dfs 中频繁调用 int()
            n = len(high_s)
            low_s = list(map(int, bin(left)[2:].zfill(n)))  # 添加前导零,长度和 high_s 对齐
    
            # 在 dfs 的过程中,统计二进制中的 1 的个数 cnt1
            @cache  # 缓存装饰器,避免重复计算 dfs(一行代码实现记忆化)
            def dfs(i: int, cnt1: int, limit_low: bool, limit_high: bool) -> int:
                if i == n:
                    return 1 if cnt1 in primes else 0
    
                lo = low_s[i] if limit_low else 0
                hi = high_s[i] if limit_high else 1
    
                res = 0
                for d in range(lo, hi + 1):
                    res += dfs(i + 1, cnt1 + d, limit_low and d == lo, limit_high and d == hi)
                return res
    
            return dfs(0, 0, True, True)
    
    class Solution {
        private static final Set<Integer> primes = Set.of(2, 3, 5, 7, 11, 13, 17, 19);
    
        public int countPrimeSetBits(int left, int right) {
            int n = 32 - Integer.numberOfLeadingZeros(right);
            int[][] memo = new int[n][n + 1];
            for (int[] row : memo) {
                Arrays.fill(row, -1);
            }
            return dfs(n - 1, 0, true, true, left, right, memo);
        }
    
        // 在 dfs 的过程中,统计二进制中的 1 的个数 cnt1
        private int dfs(int i, int cnt1, boolean limitLow, boolean limitHigh, int left, int right, int[][] memo) {
            if (i < 0) {
                return primes.contains(cnt1) ? 1 : 0;
            }
            if (!limitLow && !limitHigh && memo[i][cnt1] != -1) {
                return memo[i][cnt1];
            }
    
            int lo = limitLow ? left >> i & 1 : 0;
            int hi = limitHigh ? right >> i & 1 : 1;
    
            int res = 0;
            for (int d = lo; d <= hi; d++) {
                res += dfs(i - 1, cnt1 + d, limitLow && d == lo, limitHigh && d == hi, left, right, memo);
            }
    
            if (!limitLow && !limitHigh) {
                memo[i][cnt1] = res;
            }
            return res;
        }
    }
    
    class Solution {
        // 注:也可以用哈希集合做,由于本题质数很少,用数组也可以
        static constexpr int primes[] = {2, 3, 5, 7, 11, 13, 17, 19};
    
    public:
        int countPrimeSetBits(int left, int right) {
            int n = bit_width((uint32_t) right);
            vector memo(n, vector<int>(n + 1, -1));
    
            // 在 dfs 的过程中,统计二进制中的 1 的个数 cnt1
            auto dfs = [&](this auto&& dfs, int i, int cnt1, bool limit_low, bool limit_high) -> int {
                if (i < 0) {
                    return ranges::contains(primes, cnt1);
                }
                if (!limit_low && !limit_high && memo[i][cnt1] != -1) {
                    return memo[i][cnt1];
                }
    
                int lo = limit_low ? left >> i & 1 : 0;
                int hi = limit_high ? right >> i & 1 : 1;
    
                int res = 0;
                for (int d = lo; d <= hi; d++) {
                    res += dfs(i - 1, cnt1 + d, limit_low && d == lo, limit_high && d == hi);
                }
    
                if (!limit_low && !limit_high) {
                    memo[i][cnt1] = res;
                }
                return res;
            };
    
            return dfs(n - 1, 0, true, true);
        }
    };
    
    // 注:也可以用哈希集合做,由于本题质数很少,用数组也可以
    var primes = []int{2, 3, 5, 7, 11, 13, 17, 19}
    
    func countPrimeSetBits(left int, right int) int {
    n := bits.Len(uint(right))
    memo := make([][]int, n)
    for i := range memo {
    memo[i] = make([]int, n+1)
    for j := range memo[i] {
    memo[i][j] = -1
    }
    }
    
    // 在 dfs 的过程中,统计二进制中的 1 的个数 cnt1
    var dfs func(int, int, bool, bool) int
    dfs = func(i, cnt1 int, limitLow, limitHigh bool) (res int) {
    if i < 0 {
    if slices.Contains(primes, cnt1) {
    return 1
    }
    return 0
    }
    if !limitLow && !limitHigh {
    p := &memo[i][cnt1]
    if *p >= 0 {
    return *p
    }
    defer func() { *p = res }()
    }
    
    lo := 0
    if limitLow {
    lo = left >> i & 1
    }
    hi := 1
    if limitHigh {
    hi = right >> i & 1
    }
    
    for d := lo; d <= hi; d++ {
    res += dfs(i-1, cnt1+d, limitLow && d == lo, limitHigh && d == hi)
    }
    return
    }
    
    return dfs(n-1, 0, true, true)
    }
    

    复杂度分析

    • 时间复杂度:$\mathcal{O}(\log^2 \textit{right})$。由于每个状态只会计算一次,动态规划的时间复杂度 $=$ 状态个数 $\times$ 单个状态的计算时间。本题状态个数等于 $\mathcal{O}(\log^2 \textit{right})$,单个状态的计算时间为 $\mathcal{O}(1)$,所以总的时间复杂度为 $\mathcal{O}(\log^2 \textit{right})$。
    • 空间复杂度:$\mathcal{O}(\log^2 \textit{right})$。保存多少状态,就需要多少空间。

    方法三:组合数学

    primes = [2, 3, 5, 7, 11, 13, 17, 19]
    
    class Solution:
        def calc(self, high: int) -> int:
            # 转换成计算 < high + 1 的合法正整数个数
            # 这样转换可以方便下面的代码把 high 也算进来
            high += 1
            res = ones = 0
            for i in range(high.bit_length() - 1, -1, -1):
                if high >> i & 1 == 0:
                    continue
                # 如果这一位填 0,那么后面可以随便填
                # 问题变成在 i 个位置中填 k 个 1 的方案数,满足 ones + k 是质数
                for p in primes:
                    k = p - ones  # 剩余需要填的 1 的个数
                    if k > i:
                        break
                    if k >= 0:
                        res += comb(i, k)
                # 这一位填 1,继续计算
                ones += 1
            return res
    
        def countPrimeSetBits(self, left: int, right: int) -> int:
            return self.calc(right) - self.calc(left - 1)
    
    MX = 20
    comb = [[0] * MX for _ in range(MX)]
    for i in range(MX):
        comb[i][0] = 1
        for j in range(1, i + 1):
            comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]
    
    primes = [2, 3, 5, 7, 11, 13, 17, 19]
    
    class Solution:
        def calc(self, high: int) -> int:
            # 转换成计算 < high + 1 的合法正整数个数
            # 这样转换可以方便下面的代码把 high 也算进来
            high += 1
            res = ones = 0
            for i in range(high.bit_length() - 1, -1, -1):
                if high >> i & 1 == 0:
                    continue
                # 如果这一位填 0,那么后面可以随便填
                # 问题变成在 i 个位置中填 k 个 1 的方案数,满足 ones + k 是质数
                for p in primes:
                    k = p - ones  # 剩余需要填的 1 的个数
                    if k > i:
                        break
                    if k >= 0:
                        res += comb[i][k]
                # 这一位填 1,继续计算
                ones += 1
            return res
    
        def countPrimeSetBits(self, left: int, right: int) -> int:
            return self.calc(right) - self.calc(left - 1)
    
    class Solution {
        private static final int MX = 20;
        private static final int[][] comb = new int[MX][MX];
        private static final int[] primes = {2, 3, 5, 7, 11, 13, 17, 19};
        private static boolean initialized = false;
    
        // 这样写比 static block 快
        public Solution() {
            if (initialized) {
                return;
            }
            initialized = true;
    
            // 预处理组合数
            for (int i = 0; i < MX; i++) {
                comb[i][0] = 1;
                for (int j = 1; j <= i; j++) {
                    comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j];
                }
            }
        }
    
        public int countPrimeSetBits(int left, int right) {
            return calc(right) - calc(left - 1);
        }
    
        private int calc(int high) {
            // 转换成计算 < high + 1 的合法正整数个数
            // 这样转换可以方便下面的代码把 high 也算进来
            high++;
            int res = 0;
            int ones = 0;
            for (int i = 31 - Integer.numberOfLeadingZeros(high); i >= 0; i--) {
                if ((high >> i & 1) == 0) {
                    continue;
                }
                // 如果这一位填 0,那么后面可以随便填
                // 问题变成在 pos 个位置中填 k 个 1 的方案数,满足 ones + k 是质数
                for (int p : primes) {
                    int k = p - ones; // 剩余需要填的 1 的个数
                    if (k > i) {
                        break;
                    }
                    if (k >= 0) {
                        res += comb[i][k];
                    }
                }
                ones++; // 这一位填 1,继续计算
            }
            return res;
        }
    }
    
    constexpr int MX = 20;
    int comb[MX][MX];
    
    auto init = [] {
        // 预处理组合数
        for (int i = 0; i < MX; i++) {
            comb[i][0] = 1;
            for (int j = 1; j <= i; j++) {
                comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j];
            }
        }
        return 0;
    }();
    
    class Solution {
        static constexpr int primes[] = {2, 3, 5, 7, 11, 13, 17, 19};
    
        int calc(int high) {
            // 转换成计算 < high + 1 的合法正整数个数
            // 这样转换可以方便下面的代码把 high 也算进来
            high++;
            int res = 0, ones = 0;
            for (int i = bit_width((uint32_t) high) - 1; i >= 0; i--) {
                if ((high >> i & 1) == 0) {
                    continue;
                }
                // 如果这一位填 0,那么后面可以随便填
                // 问题变成在 i 个位置中填 k 个 1 的方案数,满足 ones + k 是质数
                for (int p : primes) {
                    int k = p - ones; // 剩余需要填的 1 的个数
                    if (k > i) {
                        break;
                    }
                    if (k >= 0) {
                        res += comb[i][k];
                    }
                }
                ones++; // 这一位填 1,继续计算
            }
            return res;
        }
    
    public:
        int countPrimeSetBits(int left, int right) {
            return calc(right) - calc(left - 1);
        }
    };
    
    const mx = 20
    
    var comb [mx][mx]int
    var primes = []int{2, 3, 5, 7, 11, 13, 17, 19}
    
    func init() {
    // 预处理组合数
    for i := range comb {
    comb[i][0] = 1
    for j := 1; j <= i; j++ {
    comb[i][j] = comb[i-1][j-1] + comb[i-1][j]
    }
    }
    }
    
    func calc(high int) (res int) {
    // 转换成计算 < high + 1 的合法正整数个数
    // 这样转换可以方便下面的代码把 high 也算进来
    high++
    ones := 0
    for i := bits.Len(uint(high)) - 1; i >= 0; i-- {
    if high>>i&1 == 0 {
    continue
    }
    // 如果这一位填 0,那么后面可以随便填
    // 问题变成在 i 个位置中填 k 个 1 的方案数,满足 ones + k 是质数
    for _, p := range primes {
    k := p - ones // 剩余需要填的 1 的个数
    if k > i {
    break
    }
    if k >= 0 {
    res += comb[i][k]
    }
    }
    // 这一位填 1,继续计算
    ones++
    }
    return res
    }
    
    func countPrimeSetBits(left, right int) int {
    return calc(right) - calc(left-1)
    }
    

    复杂度分析

    不计入预处理的时间和空间。

    • 时间复杂度:$\mathcal{O}\left(\dfrac{\log^2 \textit{right}}{\log\log \textit{right}}\right)$。循环 $\mathcal{O}(\log \textit{right})$ 次,每次循环会遍历 $\mathcal{O}(\log \textit{right})$ 以内的质数,根据质数密度,这有 $\mathcal{O}\left(\dfrac{\log \textit{right}}{\log\log \textit{right}}\right)$ 个。预处理组合数后,计算组合数的时间为 $\mathcal{O}(1)$。
    • 空间复杂度:$\mathcal{O}(1)$。

    专题训练

    1. 动态规划题单的「十、数位 DP」。
    2. 数学题单的「§2.2 组合计数」。

    分类题单

    如何科学刷题?

    1. 滑动窗口与双指针(定长/不定长/单序列/双序列/三指针/分组循环)
    2. 二分算法(二分答案/最小化最大值/最大化最小值/第K小)
    3. 单调栈(基础/矩形面积/贡献法/最小字典序)
    4. 网格图(DFS/BFS/综合应用)
    5. 位运算(基础/性质/拆位/试填/恒等式/思维)
    6. 图论算法(DFS/BFS/拓扑排序/基环树/最短路/最小生成树/网络流)
    7. 动态规划(入门/背包/划分/状态机/区间/状压/数位/数据结构优化/树形/博弈/概率期望)
    8. 常用数据结构(前缀和/差分/栈/队列/堆/字典树/并查集/树状数组/线段树)
    9. 数学算法(数论/组合/概率期望/博弈/计算几何/随机算法)
    10. 贪心与思维(基本贪心策略/反悔/区间/字典序/数学/思维/脑筋急转弯/构造)
    11. 链表、树与回溯(前后指针/快慢指针/DFS/BFS/直径/LCA)
    12. 字符串(KMP/Z函数/Manacher/字符串哈希/AC自动机/后缀数组/子序列自动机)

    我的题解精选(已分类)

    每日一题-二进制表示中质数个计算置位🟢

    2026年2月21日 00:00

    给你两个整数 left 和 right ,在闭区间 [left, right] 范围内,统计并返回 计算置位位数为质数 的整数个数。

    计算置位位数 就是二进制表示中 1 的个数。

    • 例如, 21 的二进制表示 10101 有 3 个计算置位。

     

    示例 1:

    输入:left = 6, right = 10
    输出:4
    解释:
    6 -> 110 (2 个计算置位,2 是质数)
    7 -> 111 (3 个计算置位,3 是质数)
    9 -> 1001 (2 个计算置位,2 是质数)
    10-> 1010 (2 个计算置位,2 是质数)
    共计 4 个计算置位为质数的数字。
    

    示例 2:

    输入:left = 10, right = 15
    输出:5
    解释:
    10 -> 1010 (2 个计算置位, 2 是质数)
    11 -> 1011 (3 个计算置位, 3 是质数)
    12 -> 1100 (2 个计算置位, 2 是质数)
    13 -> 1101 (3 个计算置位, 3 是质数)
    14 -> 1110 (3 个计算置位, 3 是质数)
    15 -> 1111 (4 个计算置位, 4 不是质数)
    共计 5 个计算置位为质数的数字。
    

     

    提示:

    • 1 <= left <= right <= 106
    • 0 <= right - left <= 104

    【宫水三叶】一题双解 :「lowbit」&「分治」

    作者 AC_OIer
    2022年4月5日 08:32

    模拟 + lowbit

    利用一个 int 的二进制表示不超过 $32$,我们可以先将 $32$ 以内的质数进行打表。

    从前往后处理 $[left, right]$ 中的每个数 $x$,利用 lowbit 操作统计 $x$ 共有多少位 $1$,记为 $cnt$,若 $cnt$ 为质数,则对答案进行加一操作。

    代码:

    ###Java

    class Solution {
        static boolean[] hash = new boolean[40];
        static {
            int[] nums = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
            for (int x : nums) hash[x] = true;
        }
        public int countPrimeSetBits(int left, int right) {
            int ans = 0;
            for (int i = left; i <= right; i++) {
                int x = i, cnt = 0;
                while (x != 0 && ++cnt >= 0) x -= (x & -x);
                if (hash[cnt]) ans++;
            }
            return ans;
        }
    }
    
    • 时间复杂度:$O((right - left) * \log{right})$
    • 空间复杂度:$O(C)$

    模拟 + 分治

    枚举 $[left, right]$ 范围内的数总是不可避免,上述解法的复杂度取决于复杂度为 $O(\log{x})$ 的 lowbit 操作。

    而比 lowbit 更加优秀的统计「二进制 $1$ 的数量」的做法最早在 (题解) 191. 位1的个数 讲过,采用「分治」思路对二进制进行成组统计,复杂度为 $O(\log{\log{x}})$。

    代码:

    ###Java

    class Solution {
        static boolean[] hash = new boolean[40];
        static {
            int[] nums = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
            for (int x : nums) hash[x] = true;
        }
        public int countPrimeSetBits(int left, int right) {
            int ans = 0;
            for (int i = left; i <= right; i++) {
                int x = i;
                x = (x & 0x55555555) + ((x >>> 1)  & 0x55555555);
                x = (x & 0x33333333) + ((x >>> 2)  & 0x33333333);
                x = (x & 0x0f0f0f0f) + ((x >>> 4)  & 0x0f0f0f0f);
                x = (x & 0x00ff00ff) + ((x >>> 8)  & 0x00ff00ff);
                x = (x & 0x0000ffff) + ((x >>> 16) & 0x0000ffff);
                if (hash[x]) ans++;
            }
            return ans;
        }
    }
    
    • 时间复杂度:$O((right - left) * \log{\log{right}})$
    • 空间复杂度:$O(C)$

    其他「位运算」相关内容

    考虑加练其他「位运算」相关内容 🍭🍭🍭

    题目 题解 难度 推荐指数
    137. 只出现一次的数字 II LeetCode 题解链接 中等 🤩🤩🤩
    190. 颠倒二进制位 LeetCode 题解链接 简单 🤩🤩🤩
    191. 位1的个数 LeetCode 题解链接 简单 🤩🤩🤩
    231. 2 的幂 LeetCode 题解链接 简单 🤩🤩🤩
    338. 比特位计数 LeetCode 题解链接 简单 🤩🤩🤩
    342. 4的幂 LeetCode 题解链接 简单 🤩🤩🤩
    461. 汉明距离 LeetCode 题解链接 简单 🤩🤩🤩🤩
    477. 汉明距离总和 LeetCode 题解链接 简单 🤩🤩🤩🤩
    1178. 猜字谜 LeetCode 题解链接 困难 🤩🤩🤩🤩
    剑指 Offer 15. 二进制中1的个数 LeetCode 题解链接 简单 🤩🤩🤩

    注:以上目录整理来自 wiki,任何形式的转载引用请保留出处。


    最后

    如果有帮助到你,请给题解点个赞和收藏,让更多的人看到 ~ ("▔□▔)/

    也欢迎你 关注我 和 加入我们的「组队打卡」小群 ,提供写「证明」&「思路」的高质量题解。

    所有题解已经加入 刷题指南,欢迎 star 哦 ~

    二进制表示中质数个计算置位

    2022年4月2日 18:44

    方法一:数学 + 位运算

    我们可以枚举 $[\textit{left},\textit{right}]$ 范围内的每个整数,挨个判断是否满足题目要求。

    对于每个数 $x$,我们需要解决两个问题:

    1. 如何求出 $x$ 的二进制中的 $1$ 的个数,见「191. 位 1 的个数」,下面代码用库函数实现;
    2. 如何判断一个数是否为质数,见「204. 计数质数」的「官方解法」的方法一(注意 $0$ 和 $1$ 不是质数)。

    ###Python

    class Solution:
        def isPrime(self, x: int) -> bool:
            if x < 2:
                return False
            i = 2
            while i * i <= x:
                if x % i == 0:
                    return False
                i += 1
            return True
    
        def countPrimeSetBits(self, left: int, right: int) -> int:
            return sum(self.isPrime(x.bit_count()) for x in range(left, right + 1))
    

    ###C++

    class Solution {
        bool isPrime(int x) {
            if (x < 2) {
                return false;
            }
            for (int i = 2; i * i <= x; ++i) {
                if (x % i == 0) {
                    return false;
                }
            }
            return true;
        }
    
    public:
        int countPrimeSetBits(int left, int right) {
            int ans = 0;
            for (int x = left; x <= right; ++x) {
                if (isPrime(__builtin_popcount(x))) {
                    ++ans;
                }
            }
            return ans;
        }
    };
    

    ###Java

    class Solution {
        public int countPrimeSetBits(int left, int right) {
            int ans = 0;
            for (int x = left; x <= right; ++x) {
                if (isPrime(Integer.bitCount(x))) {
                    ++ans;
                }
            }
            return ans;
        }
    
        private boolean isPrime(int x) {
            if (x < 2) {
                return false;
            }
            for (int i = 2; i * i <= x; ++i) {
                if (x % i == 0) {
                    return false;
                }
            }
            return true;
        }
    }
    

    ###C#

    public class Solution {
        public int CountPrimeSetBits(int left, int right) {
            int ans = 0;
            for (int x = left; x <= right; ++x) {
                if (IsPrime(BitCount(x))) {
                    ++ans;
                }
            }
            return ans;
        }
    
        private bool IsPrime(int x) {
            if (x < 2) {
                return false;
            }
            for (int i = 2; i * i <= x; ++i) {
                if (x % i == 0) {
                    return false;
                }
            }
            return true;
        }
    
        private static int BitCount(int i) {
            i = i - ((i >> 1) & 0x55555555);
            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
            i = (i + (i >> 4)) & 0x0f0f0f0f;
            i = i + (i >> 8);
            i = i + (i >> 16);
            return i & 0x3f;
        }
    }
    

    ###go

    func isPrime(x int) bool {
        if x < 2 {
            return false
        }
        for i := 2; i*i <= x; i++ {
            if x%i == 0 {
                return false
            }
        }
        return true
    }
    
    func countPrimeSetBits(left, right int) (ans int) {
        for x := left; x <= right; x++ {
            if isPrime(bits.OnesCount(uint(x))) {
                ans++
            }
        }
        return
    }
    

    ###C

    bool isPrime(int x) {
        if (x < 2) {
            return false;
        }
        for (int i = 2; i * i <= x; ++i) {
            if (x % i == 0) {
                return false;
            }
        }
        return true;
    }
    
    int countPrimeSetBits(int left, int right){
        int ans = 0;
        for (int x = left; x <= right; ++x) {
            if (isPrime(__builtin_popcount(x))) {
                ++ans;
            }
        }
        return ans;
    }
    

    ###JavaScript

    var countPrimeSetBits = function(left, right) {
        let ans = 0;
        for (let x = left; x <= right; ++x) {
            if (isPrime(bitCount(x))) {
                ++ans;
            }
        }
        return ans;
    };
    
    const isPrime = (x) => {
        if (x < 2) {
            return false;
        }
        for (let i = 2; i * i <= x; ++i) {
            if (x % i === 0) {
                return false;
            }
        }
        return true;
    }
    
    const bitCount = (x) => {
        return x.toString(2).split('0').join('').length;
    }
    

    复杂度分析

    • 时间复杂度:$O((\textit{right}-\textit{left})\sqrt{\log\textit{right}})$。二进制中 $1$ 的个数为 $O(\log\textit{right})$,判断值为 $x$ 的数是否为质数的时间为 $O(\sqrt{x})$。

    • 空间复杂度:$O(1)$。我们只需要常数的空间保存若干变量。

    方法二:判断质数优化

    注意到 $\textit{right} \le 10^6 < 2^{20}$,因此二进制中 $1$ 的个数不会超过 $19$,而不超过 $19$ 的质数只有

    $$
    2, 3, 5, 7, 11, 13, 17, 19
    $$

    我们可以用一个二进制数 $\textit{mask}=665772=10100010100010101100_{2}$ 来存储这些质数,其中 $\textit{mask}$ 二进制的从低到高的第 $i$ 位为 $1$ 表示 $i$ 是质数,为 $0$ 表示 $i$ 不是质数。

    设整数 $x$ 的二进制中 $1$ 的个数为 $c$,若 $\textit{mask}$ 按位与 $2^c$ 不为 $0$,则说明 $c$ 是一个质数。

    ###Python

    class Solution:
        def countPrimeSetBits(self, left: int, right: int) -> int:
            return sum(((1 << x.bit_count()) & 665772) != 0 for x in range(left, right + 1))
    

    ###C++

    class Solution {
    public:
        int countPrimeSetBits(int left, int right) {
            int ans = 0;
            for (int x = left; x <= right; ++x) {
                if ((1 << __builtin_popcount(x)) & 665772) {
                    ++ans;
                }
            }
            return ans;
        }
    };
    

    ###Java

    class Solution {
        public int countPrimeSetBits(int left, int right) {
            int ans = 0;
            for (int x = left; x <= right; ++x) {
                if (((1 << Integer.bitCount(x)) & 665772) != 0) {
                    ++ans;
                }
            }
            return ans;
        }
    }
    

    ###C#

    public class Solution {
        public int CountPrimeSetBits(int left, int right) {
            int ans = 0;
            for (int x = left; x <= right; ++x) {
                if (((1 << BitCount(x)) & 665772) != 0) {
                    ++ans;
                }
            }
            return ans;
        }
    
        private static int BitCount(int i) {
            i = i - ((i >> 1) & 0x55555555);
            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
            i = (i + (i >> 4)) & 0x0f0f0f0f;
            i = i + (i >> 8);
            i = i + (i >> 16);
            return i & 0x3f;
        }
    }
    

    ###go

    func countPrimeSetBits(left, right int) (ans int) {
        for x := left; x <= right; x++ {
            if 1<<bits.OnesCount(uint(x))&665772 != 0 {
                ans++
            }
        }
        return
    }
    

    ###C

    int countPrimeSetBits(int left, int right){
        int ans = 0;
        for (int x = left; x <= right; ++x) {
            if ((1 << __builtin_popcount(x)) & 665772) {
                ++ans;
            }
        }
        return ans;
    }
    

    ###JavaScript

    var countPrimeSetBits = function(left, right) {
        let ans = 0;
        for (let x = left; x <= right; ++x) {
            if (((1 << bitCount(x)) & 665772) != 0) {
                ++ans;
            }
        }
        return ans;
    };
    
    const bitCount = (x) => {
        return x.toString(2).split('0').join('').length;
    }
    

    复杂度分析

    • 时间复杂度:$O(\textit{right}-\textit{left})$。

    • 空间复杂度:$O(1)$。我们只需要常数的空间保存若干变量。

    二进制表示中质数个计算置位 - Java超越99%的简单写法

    作者 FlyChenKai
    2019年8月14日 09:34

    解题思路

    • L,R 最大为 $10^6$,转换为二进制,有 20 位,故 计算置位 个数不会超过 20。即求出 20 以内的质数列表即可。
    • 使用 Integer.bitCount(i) 函数可快速求得 i 的二进制形式中 1 的个数。

    代码:

    class Solution {
       public int countPrimeSetBits(int L, int R) {
            //0-20的质数列表,prime[i]为1,则i为质数
            int[] primes = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1};
            int res = 0;
            for (int i = L; i <= R; i++) {
                int t = Integer.bitCount(i);
                res += primes[t];
            }
            return res;
        }
    }
    

    每日一题-特殊的二进制字符串🔴

    2026年2月20日 00:00

    特殊的二进制字符串 是具有以下两个性质的二进制序列:

    • 0 的数量与 1 的数量相等。
    • 二进制序列的每一个前缀码中 1 的数量要大于等于 0 的数量。

    给定一个特殊的二进制字符串 s

    一次移动操作包括选择字符串 s 中的两个连续的、非空的、特殊子串,并交换它们。两个字符串是连续的,如果第一个字符串的最后一个字符与第二个字符串的第一个字符的索引相差正好为 1。

    返回在字符串上应用任意次操作后可能得到的字典序最大的字符串。

     

    示例 1:

    输入: S = "11011000"
    输出: "11100100"
    解释:
    将子串 "10" (在 s[1] 出现) 和 "1100" (在 s[3] 出现)进行交换。
    这是在进行若干次操作后按字典序排列最大的结果。
    

    示例 2:

    输入:s = "10"
    输出:"10"
    

     

    提示:

    • 1 <= s.length <= 50
    • s[i] 为 '0' 或 '1'
    • s 是一个特殊的二进制字符串。

    【宫水三叶】经典构造题

    作者 AC_OIer
    2022年8月8日 09:39

    构造

    我们可以定义每个字符的得分:字符 1 得分为 $1$ 分,字符 0 得分为 $-1$ 分。

    根据题目对「特殊字符串」的定义可知,给定字符串 s 的总得分为 $0$,且任意前缀串不会出现得分为负数的情况。

    考虑将 s 进行划分为多个足够小特殊字符串 item(足够小的含义为每个 item 无法再进行划分),每个 item 的总得分为 $0$。根据 s 定义,必然可恰好划分为多个 item

    每次操作可以将相邻特殊字符串进行交换,于是问题转换为将 s 进行重排,求其重排后字典序最大的方案。

    首先可以证明一个合法 item 必然满足 1...0 的形式,可通过「反证法」进行进行证明:定义了 item 总得分为 $0$,且长度不为 $0$,因此必然有 10若第一位字符为 0,则必然能够从第一位字符作为起点,找到一个得分为负数的子串,这与 s 本身的定义冲突(s 中不存在得分为负数的前缀串);若最后一位为 1,根据 item 总得分为 $0$,可知当前 item 去掉最后一位后得分为负,也与 s 本身定义冲突(s 中不存在得分为负数的前缀串)。

    因此可将构造分两步进行:

    1. 对于每个 item 进行重排,使其调整为字典序最大
    2. 对于 item 之间的位置进行重排,使其整体字典序最大

    由于题目没有规定重排后的性质,为第一步调整和第二步调整的保持相对独立,我们只能对 item 中的 1...0 中的非边缘部分进行调整(递归处理子串部分)。

    假设所有 item 均被处理后,考虑如何进行重排能够使得最终方案字典序最大。

    若有两个 item,分别为 ab,我们可以根据拼接结果 abba 的字典序大小来决定将谁放在前面。

    这样根据「排序比较逻辑」需要证明在集合上具有「全序关系」:

    我们使用符号 $@$ 来代指我们的「排序」逻辑:

    • 如果 $a$ 必须排在 $b$ 的前面,我们记作 $a @ b$;
    • 如果 $a$ 必须排在 $b$ 的后面,我们记作 $b @ a$;
    • 如果 $a$ 既可以排在 $b$ 的前面,也可以排在 $b$ 的后面,我们记作 $a#b$;

    2.1 完全性

    具有完全性是指从集合 items 中任意取出两个元素 $a$ 和 $b$,必然满足 $a @ b$、$b @ a$ 和 $a#b$ 三者之一。

    这点其实不需要额外证明,因为由 $a$ 和 $b$ 拼接的字符串 $ab$ 和 $ba$ 所在「字典序大小关系中」要么完全相等,要么具有明确的字典序大小关系,导致 $a$ 必须排在前面或者后面。

    2.2 反对称性

    具有反对称性是指由 $a@b$ 和 $b@a$ 能够推导出 $a#b$。

    $a@b$ 说明字符串 $ab$ 的字典序大小数值要比字符串 $ba$ 字典序大小数值大。

    $b@a$ 说明字符串 $ab$ 的字典序大小数值要比字符串 $ba$ 字典序大小数值小。

    这样,基于「字典序本身满足全序关系」和「数学上的 $a \geqslant b$ 和 $a \leqslant b$ 可推导出 $a = b$」。

    得证 $a@b$ 和 $b@a$ 能够推导出 $a#b$。

    2.3 传递性

    具有传递性是指由 $a@b$ 和 $b@c$ 能够推导出 $a@c$。

    我们可以利用「两个等长的拼接字符串,字典序大小关系与数值大小关系一致」这一性质来证明,因为字符串 $ac$ 和 $ca$ 必然是等长的。

    接下来,让我们从「自定义排序逻辑」出发,换个思路来证明 $a@c$:

    image.png

    然后我们只需要证明在不同的 $i$ $j$ 关系之间(共三种情况),$a@c$ 恒成立即可:

    1. 当 $i == j$ 的时候:

    image.png

    1. 当 $i > j$ 的时候:

    image.png

    1. 当 $i < j$ 的时候:

    image.png

    综上,我们证明了无论在何种情况下,只要有 $a@b$ 和 $b@c$ 的话,那么 $a@c$ 恒成立。

    我们之所以能这样证明「传递性」,本质是利用了自定义排序逻辑中「对于确定任意元素 $a$ 和 $b$ 之间的排序关系只依赖于 $a$ 和 $b$ 的第一个不同元素之间的大小关系」这一性质。

    最终,我们证明了该「排序比较逻辑」必然能排序出字典序最大的方案。

    代码:

    ###Java

    class Solution {
        public String makeLargestSpecial(String s) {
            if (s.length() == 0) return s;
            List<String> list = new ArrayList<>();
            char[] cs = s.toCharArray();
            for (int i = 0, j = 0, k = 0; i < cs.length; i++) {
                k += cs[i] == '1' ? 1 : -1;
                if (k == 0) {
                    list.add("1" + makeLargestSpecial(s.substring(j + 1, i)) + "0");
                    j = i + 1;
                }
            }
            Collections.sort(list, (a, b)->(b + a).compareTo(a + b));
            StringBuilder sb = new StringBuilder();
            for (String str : list) sb.append(str);
            return sb.toString();
        }
    }
    

    ###TypeScript

    function makeLargestSpecial(s: string): string {
        const list = new Array<string>()
        for (let i = 0, j = 0, k = 0; i < s.length; i++) {
            k += s[i] == '1' ? 1 : -1
            if (k == 0) {
                list.push('1' + makeLargestSpecial(s.substring(j + 1, i)) + '0')
                j = i + 1
            }
        }
        list.sort((a, b)=>(b + a).localeCompare(a + b));
        return [...list].join("")
    };
    
    • 时间复杂度:$O(n^2)$
    • 空间复杂度:$O(n)$

    最后

    如果有帮助到你,请给题解点个赞和收藏,让更多的人看到 ~ ("▔□▔)/

    也欢迎你 关注我 和 加入我们的「组队打卡」小群 ,提供写「证明」&「思路」的高质量题解。

    所有题解已经加入 刷题指南,欢迎 star 哦 ~

    特殊的二进制序列【递归】

    2022年8月8日 07:58

    方法一:递归

    我们可以把特殊的二进制序列看作"有效的括号",1代表左括号,0代表右括号。

    • 0的数量与1的数量相等,代表左右括号数量相等。
    • 二进制序列的每一个前缀码中1的数量要大于等于0的数量,代表有效的括号,每一个左括号都有右括号匹配,并且左括号在前。

    比如:"11011000"可以看作"(()(()))"。

    两个连续且非空的特殊的子串,然后将它们交换,代表着交换两个相邻的两个有效括号。

    我们可以将题进行如下划分,把每一个有效的括号匹配都看作一部分,然后进行排序,内部也进行排序处理,例如:
    image.png

    代码如下

    ###java

        public String makeLargestSpecial(String s) {
            if (s.length() == 0) {
                return "";
            }
            List<String> list = new ArrayList<>();
            int count = 0, last = 0;
            for (int i = 0, cur = 0; i < s.length(); i++, cur++) {
                if (s.charAt(i) == '1') {
                    count++;
                } else {
                    count--;
                }
                //一组有效的括号匹配 去掉括号进行 内部排序
                if (count == 0) {
                    String str = "1" + makeLargestSpecial(s.substring(last + 1, cur)) + "0";
                    list.add(str);
                    last = cur + 1;
                }
            }
            //进行排序,根据冒泡排序,交换两个相邻的元素进行排序,总能让内部的括号由大到小排列
            list.sort(Comparator.reverseOrder());
            //拼成完整的字符串
            StringBuilder sb = new StringBuilder();
            for (String str : list) {
                sb.append(str);
            }
            return sb.toString();
        }
    

    写题解不易,如果对您有帮助,记得关注 + 点赞 + 收藏呦!!!
    每天都会更新每日一题题解,大家加油!!

    转换为括号字符串,就很容易了

    作者 newhar
    2020年5月24日 19:13

    解题思路

    相信好多人看到题目中 “特殊的二进制序列” 的定义就懵逼了,这到底是什么鬼?
    所以题目最难的地方就是 “不说人话”。其实只要想到这种定义就是 “有效的括号字符串” 就容易许多了,“1” 代表 “(”,“0” 代表 “)”。

    • 0 和 1 的数量相等。 → “右括号” 数量和 “左括号” 相同。
    • 二进制序列的每一个前缀码中 1 的数量要大于等于 0 的数量。→ “右括号” 必须能够找到一个 “左括号” 匹配。

    再看题目中 “操作” 的定义:首先选择 S 的两个 连续 且非空的 特殊 的子串,然后将它们交换。
    翻译过来就是:选择 S 中的两个 相邻有效的括号字符串,然后交换即可。

    现在再来解决问题。首先分析 “有效的括号字符串” 的性质。

    • 一个有效的括号字符串一般能够被拆分为一段或几段,其中每一段都是 “不可拆分的有效的括号字符串”,比如,“()(())” 可以拆分为 “()” 和 “(())”。
    • 另外,“有效的括号字符串” 中的每一 “段” 内部 (即去掉最外层括号的字串)都是另一个 “有效括号字符串”,比如 “(())” 里面是 “()”。

    根据上面的规则,我们可以 递归地 将二进制序列对应的 “括号字符串” 分解。以序列 “110011100110110000” 为例:
    image.png

    我们容易想到一种 递归地 解题思路。

    • 第一步,将字符串拆分成一段或几段 “不可拆分的有效的括号字符串”。
    • 第二步,将每一段 内部 的子串(也是 “有效的括号字符串”)分别重新排列成字典序最大的字符串(解决子问题)。
    • 第三步,由于 每一对相邻的段都可以交换,因此无限次交换相当于我们可以把各个段以 任意顺序 排列。我们要找到字典序最大的排列。
      这里有一个值得思考的地方:由于每一 “段” 必会以 “0” 结尾,因此只要将 “字典序最大” 的串放在第一位,“字典序次大” 的串放在第二位,...,就可以得到字典序最大的排列。(即将各个段按照字典序从大到小排序即可)。

    代码

    ###python

    class Solution:
        def makeLargestSpecial(self, s: str) -> str:
            cur, last = 0, 0
            ret = []
            for i in range(len(s)):
                cur += 1 if s[i] == '1' else -1
                if cur == 0:
                    ret.append('1' + self.makeLargestSpecial(s[last + 1 : i]) + '0')
                    last = i + 1
            return ''.join(sorted(ret, reverse=True))
    

    ###c++

    class Solution {
    public:
        string makeLargestSpecial(string s) {
            vector<string> v;
            for(int i = 0, cur = 0, last = 0; i < s.size(); ++i) {
                (s[i] == '1')? cur++ : cur--;
                if(cur == 0) {
                    v.push_back("1");
                    v.back() += makeLargestSpecial(s.substr(last + 1, i - last - 1)) + '0';
                    last = i + 1;
                }
            }
            sort(v.begin(), v.end(), greater<string>());
    
            string res;
            for(auto& r : v) {
                res += r;
            }
            return res;
        }
    };
    

    每日一题-计数二进制子串🟢

    2026年2月19日 00:00

    给定一个字符串 s,统计并返回具有相同数量 01 的非空(连续)子字符串的数量,并且这些子字符串中的所有 0 和所有 1 都是成组连续的。

    重复出现(不同位置)的子串也要统计它们出现的次数。

     

    示例 1:

    输入:s = "00110011"
    输出:6
    解释:6 个子串满足具有相同数量的连续 1 和 0 :"0011"、"01"、"1100"、"10"、"0011" 和 "01" 。
    注意,一些重复出现的子串(不同位置)要统计它们出现的次数。
    另外,"00110011" 不是有效的子串,因为所有的 0(还有 1 )没有组合在一起。

    示例 2:

    输入:s = "10101"
    输出:4
    解释:有 4 个子串:"10"、"01"、"10"、"01" ,具有相同数量的连续 1 和 0 。
    

     

    提示:

    • 1 <= s.length <= 105
    • s[i]'0''1'

    一次遍历,简洁写法(Python/Java/C++/C/Go/JS/Rust)

    作者 endlesscheng
    2026年2月7日 09:22

    题意:子串必须形如 $\underbrace{\texttt{0}\cdots \texttt{0}}{k\ 个\ \texttt{0}}\underbrace{\texttt{1}\cdots \texttt{1}}{k\ 个\ \texttt{1}}$ 或者 $\underbrace{\texttt{1}\cdots \texttt{1}}{k\ 个\ \texttt{1}}\underbrace{\texttt{0}\cdots \texttt{0}}{k\ 个\ \texttt{0}}$。只能有一段 $\texttt{0}$ 和一段 $\texttt{1}$,不能是 $\texttt{00111}$(两段长度不等)或者 $\texttt{010}$(超过两段)等。

    例如 $s = \texttt{001110000}$,按照连续相同字符,分成三组 $\texttt{00},\texttt{111},\texttt{0000}$。

    • 在前两组中,我们可以得到 $2$ 个合法子串:$\texttt{0011}$ 和 $\texttt{01}$。
    • 在后两组中,我们可以得到 $3$ 个合法子串:$\texttt{111000}$、$\texttt{1100}$ 和 $\texttt{10}$。

    一般地,遍历 $s$,按照连续相同字符分组,计算每一组的长度。设当前这组的长度为 $\textit{cur}$,上一组的长度为 $\textit{pre}$,那么当前这组和上一组,能得到 $\min(\textit{pre},\textit{cur})$ 个合法子串,加到答案中。

    ###py

    class Solution:
        def countBinarySubstrings(self, s: str) -> int:
            n = len(s)
            pre = cur = ans = 0
            for i in range(n):
                cur += 1
                if i == n - 1 or s[i] != s[i + 1]:
                    # 遍历到了这一组的末尾
                    ans += min(pre, cur)
                    pre = cur
                    cur = 0
            return ans
    

    ###java

    class Solution {
        public int countBinarySubstrings(String S) {
            char[] s = S.toCharArray();
            int n = s.length;
            int pre = 0;
            int cur = 0;
            int ans = 0;
            for (int i = 0; i < n; i++) {
                cur++;
                if (i == n - 1 || s[i] != s[i + 1]) {
                    // 遍历到了这一组的末尾
                    ans += Math.min(pre, cur);
                    pre = cur;
                    cur = 0;
                }
            }
            return ans;
        }
    }
    

    ###cpp

    class Solution {
    public:
        int countBinarySubstrings(string s) {
            int n = s.size();
            int pre = 0, cur = 0, ans = 0;
            for (int i = 0; i < n; i++) {
                cur++;
                if (i == n - 1 || s[i] != s[i + 1]) {
                    // 遍历到了这一组的末尾
                    ans += min(pre, cur);
                    pre = cur;
                    cur = 0;
                }
            }
            return ans;
        }
    };
    

    ###c

    #define MIN(a, b) ((b) < (a) ? (b) : (a))
    
    int countBinarySubstrings(char* s) {
        int pre = 0, cur = 0, ans = 0;
        for (int i = 0; s[i]; i++) {
            cur++;
            if (s[i] != s[i + 1]) {
                // 遍历到了这一组的末尾
                ans += MIN(pre, cur);
                pre = cur;
                cur = 0;
            }
        }
        return ans;
    }
    

    ###go

    func countBinarySubstrings(s string) (ans int) {
    n := len(s)
    pre, cur := 0, 0
    for i := range n {
    cur++
    if i == n-1 || s[i] != s[i+1] {
    // 遍历到了这一组的末尾
    ans += min(pre, cur)
    pre = cur
    cur = 0
    }
    }
    return
    }
    

    ###js

    var countBinarySubstrings = function(s) {
        const n = s.length;
        let pre = 0, cur = 0, ans = 0;
        for (let i = 0; i < n; i++) {
            cur++;
            if (i === n - 1 || s[i] !== s[i + 1]) {
                // 遍历到了这一组的末尾
                ans += Math.min(pre, cur);
                pre = cur;
                cur = 0;
            }
        }
        return ans;
    };
    

    ###rust

    impl Solution {
        pub fn count_binary_substrings(s: String) -> i32 {
            let s = s.as_bytes();
            let n = s.len();
            let mut pre = 0;
            let mut cur = 0;
            let mut ans = 0;
            for i in 0..n {
                cur += 1;
                if i == n - 1 || s[i] != s[i + 1] {
                    // 遍历到了这一组的末尾
                    ans += pre.min(cur);
                    pre = cur;
                    cur = 0;
                }
            }
            ans
        }
    }
    

    复杂度分析

    • 时间复杂度:$\mathcal{O}(n)$,其中 $n$ 是 $s$ 的长度。
    • 空间复杂度:$\mathcal{O}(1)$。

    专题训练

    见下面双指针题单的「六、分组循环」。

    分类题单

    如何科学刷题?

    1. 滑动窗口与双指针(定长/不定长/单序列/双序列/三指针/分组循环)
    2. 二分算法(二分答案/最小化最大值/最大化最小值/第K小)
    3. 单调栈(基础/矩形面积/贡献法/最小字典序)
    4. 网格图(DFS/BFS/综合应用)
    5. 位运算(基础/性质/拆位/试填/恒等式/思维)
    6. 图论算法(DFS/BFS/拓扑排序/基环树/最短路/最小生成树/网络流)
    7. 动态规划(入门/背包/划分/状态机/区间/状压/数位/数据结构优化/树形/博弈/概率期望)
    8. 常用数据结构(前缀和/差分/栈/队列/堆/字典树/并查集/树状数组/线段树)
    9. 数学算法(数论/组合/概率期望/博弈/计算几何/随机算法)
    10. 贪心与思维(基本贪心策略/反悔/区间/字典序/数学/思维/脑筋急转弯/构造)
    11. 链表、树与回溯(前后指针/快慢指针/DFS/BFS/直径/LCA)
    12. 字符串(KMP/Z函数/Manacher/字符串哈希/AC自动机/后缀数组/子序列自动机)

    我的题解精选(已分类)

    欢迎关注 B站@灵茶山艾府

    【计数二进制子串】计数

    作者 ikaruga
    2020年8月10日 10:00

    思路

    1. 对于 000111 来说,符合要求的子串是 000111 0011 01
      1. 不难发现,如果我们找到一段类似 000111 的数据,就可以用来统计答案
      2. 即 这样前面是连续 0/1 后面是连续 1/0 的数据
      3. 这一段的所有 3 个子串,取决于前面 0/1 的个数和后面 1/0 的个数
      4. min(cnt_pre, cnt_cur)

    图片.png

    1. 遍历时,当数字再一次改变时(或到达结尾时),意味着一段结束,并能得到这一段前面和后面数字的个数。
      1. 11101 来说,当我们遍历到最后的 1 时,1110 就是一段可以用来统计答案的数据
      2. 而末尾的 01 则是另一段可以用来统计答案的数据

    <图片.png,图片.png>

    1. 小技巧,对字符串结尾增加一个字符,可以将判断逻辑写在一个地方

    答题

    class Solution {
    public:
        int countBinarySubstrings(string s) {
            int ans = 0;
            char last = '-';
            int cnt_pre = 0;
            int cnt_cur = 0;
    
            s += '-';
            for (auto c : s) {
                if (last != c) {
                    last = c;
                    ans += min(cnt_pre, cnt_cur);
                    cnt_pre = cnt_cur;
                    cnt_cur = 0;
                }
                cnt_cur++;
            }
            return ans;
        }
    };
    

    致谢

    感谢您的观看,如果感觉还不错就点个赞吧,关注我的 力扣个人主页 ,欢迎热烈的交流!

    计数二进制子串

    2020年8月9日 21:31

    方法一:按字符分组

    思路与算法

    我们可以将字符串 $s$ 按照 $0$ 和 $1$ 的连续段分组,存在 $\textit{counts}$ 数组中,例如 $s = 00111011$,可以得到这样的 $\textit{counts}$ 数组:$\textit{counts} = {2, 3, 1, 2}$。

    这里 $\textit{counts}$ 数组中两个相邻的数一定代表的是两种不同的字符。假设 $\textit{counts}$ 数组中两个相邻的数字为 $u$ 或者 $v$,它们对应着 $u$ 个 $0$ 和 $v$ 个 $1$,或者 $u$ 个 $1$ 和 $v$ 个 $0$。它们能组成的满足条件的子串数目为 $\min { u, v }$,即一对相邻的数字对答案的贡献。

    我们只要遍历所有相邻的数对,求它们的贡献总和,即可得到答案。

    不难得到这样的实现:

    ###C++

    class Solution {
    public:
        int countBinarySubstrings(string s) {
            vector<int> counts;
            int ptr = 0, n = s.size();
            while (ptr < n) {
                char c = s[ptr];
                int count = 0;
                while (ptr < n && s[ptr] == c) {
                    ++ptr;
                    ++count;
                }
                counts.push_back(count);
            }
            int ans = 0;
            for (int i = 1; i < counts.size(); ++i) {
                ans += min(counts[i], counts[i - 1]);
            }
            return ans;
        }
    };
    

    ###Java

    class Solution {
        public int countBinarySubstrings(String s) {
            List<Integer> counts = new ArrayList<Integer>();
            int ptr = 0, n = s.length();
            while (ptr < n) {
                char c = s.charAt(ptr);
                int count = 0;
                while (ptr < n && s.charAt(ptr) == c) {
                    ++ptr;
                    ++count;
                }
                counts.add(count);
            }
            int ans = 0;
            for (int i = 1; i < counts.size(); ++i) {
                ans += Math.min(counts.get(i), counts.get(i - 1));
            }
            return ans;
        }
    }
    

    ###JavaScript

    var countBinarySubstrings = function(s) {
        const counts = [];
        let ptr = 0, n = s.length;
        while (ptr < n) {
            const c = s.charAt(ptr);
            let count = 0;
            while (ptr < n && s.charAt(ptr) === c) {
                ++ptr;
                ++count;
            }
            counts.push(count);
        }
        let ans = 0;
        for (let i = 1; i < counts.length; ++i) {
            ans += Math.min(counts[i], counts[i - 1]);
        }
        return ans;
    };
    

    ###Go

    func countBinarySubstrings(s string) int {
        counts := []int{}
        ptr, n := 0, len(s)
        for ptr < n {
            c := s[ptr]
            count := 0
            for ptr < n && s[ptr] == c {
                ptr++
                count++
            }
            counts = append(counts, count)
        }
        ans := 0
        for i := 1; i < len(counts); i++ {
            ans += min(counts[i], counts[i-1])
        }
        return ans
    }
    

    ###C

    int countBinarySubstrings(char* s) {
        int n = strlen(s);
        int counts[n], counts_len = 0;
        memset(counts, 0, sizeof(counts));
        int ptr = 0;
        while (ptr < n) {
            char c = s[ptr];
            int count = 0;
            while (ptr < n && s[ptr] == c) {
                ++ptr;
                ++count;
            }
            counts[counts_len++] = count;
        }
        int ans = 0;
        for (int i = 1; i < counts_len; ++i) {
            ans += fmin(counts[i], counts[i - 1]);
        }
        return ans;
    }
    

    ###Python

    class Solution:
        def countBinarySubstrings(self, s: str) -> int:
            counts = []
            ptr, n = 0, len(s)
            
            while ptr < n:
                c = s[ptr]
                count = 0
                while ptr < n and s[ptr] == c:
                    ptr += 1
                    count += 1
                counts.append(count)
            
            ans = 0
            for i in range(1, len(counts)):
                ans += min(counts[i], counts[i - 1])
            
            return ans
    

    ###C#

    public class Solution {
        public int CountBinarySubstrings(string s) {
            List<int> counts = new List<int>();
            int ptr = 0, n = s.Length;
            
            while (ptr < n) {
                char c = s[ptr];
                int count = 0;
                while (ptr < n && s[ptr] == c) {
                    ptr++;
                    count++;
                }
                counts.Add(count);
            }
            
            int ans = 0;
            for (int i = 1; i < counts.Count; i++) {
                ans += Math.Min(counts[i], counts[i - 1]);
            }
            
            return ans;
        }
    }
    

    ###TypeScript

    function countBinarySubstrings(s: string): number {
        const counts: number[] = [];
        let ptr = 0, n = s.length;
        
        while (ptr < n) {
            const c = s[ptr];
            let count = 0;
            while (ptr < n && s[ptr] === c) {
                ptr++;
                count++;
            }
            counts.push(count);
        }
        
        let ans = 0;
        for (let i = 1; i < counts.length; i++) {
            ans += Math.min(counts[i], counts[i - 1]);
        }
        
        return ans;
    }
    

    ###Rust

    impl Solution {
        pub fn count_binary_substrings(s: String) -> i32 {
            let mut counts = Vec::new();
            let bytes = s.as_bytes();
            let n = bytes.len();
            let mut ptr = 0;
            
            while ptr < n {
                let c = bytes[ptr];
                let mut count = 0;
                while ptr < n && bytes[ptr] == c {
                    ptr += 1;
                    count += 1;
                }
                counts.push(count);
            }
            
            let mut ans = 0;
            for i in 1..counts.len() {
                ans += counts[i].min(counts[i - 1]);
            }
            
            ans
        }
    }
    

    这个实现的时间复杂度和空间复杂度都是 $O(n)$。

    对于某一个位置 $i$,其实我们只关心 $i - 1$ 位置的 $\textit{counts}$ 值是多少,所以可以用一个 $\textit{last}$ 变量来维护当前位置的前一个位置,这样可以省去一个 $\textit{counts}$ 数组的空间。

    代码

    ###C++

    class Solution {
    public:
        int countBinarySubstrings(string s) {
            int ptr = 0, n = s.size(), last = 0, ans = 0;
            while (ptr < n) {
                char c = s[ptr];
                int count = 0;
                while (ptr < n && s[ptr] == c) {
                    ++ptr;
                    ++count;
                }
                ans += min(count, last);
                last = count;
            }
            return ans;
        }
    };
    

    ###Java

    class Solution {
        public int countBinarySubstrings(String s) {
            int ptr = 0, n = s.length(), last = 0, ans = 0;
            while (ptr < n) {
                char c = s.charAt(ptr);
                int count = 0;
                while (ptr < n && s.charAt(ptr) == c) {
                    ++ptr;
                    ++count;
                }
                ans += Math.min(count, last);
                last = count;
            }
            return ans;
        }
    }
    

    ###JavaScript

    var countBinarySubstrings = function(s) {
        let ptr = 0, n = s.length, last = 0, ans = 0;
        while (ptr < n) {
            const c = s.charAt(ptr);
            let count = 0;
            while (ptr < n && s.charAt(ptr) === c) {
                ++ptr;
                ++count;
            }
            ans += Math.min(count, last);
            last = count;
        }
        return ans;
    };
    

    ###Go

    func countBinarySubstrings(s string) int {
        var ptr, last, ans int
        n := len(s)
        for ptr < n {
            c := s[ptr]
            count := 0
            for ptr < n && s[ptr] == c {
                ptr++
                count++
            }
            ans += min(count, last)
            last = count
        }
    
        return ans
    }
    

    ###C

    int countBinarySubstrings(char* s) {
        int ptr = 0, n = strlen(s), last = 0, ans = 0;
        while (ptr < n) {
            char c = s[ptr];
            int count = 0;
            while (ptr < n && s[ptr] == c) {
                ++ptr;
                ++count;
            }
            ans += fmin(count, last);
            last = count;
        }
        return ans;
    }
    

    ###Python

    class Solution:
        def countBinarySubstrings(self, s: str) -> int:
            ptr, n = 0, len(s)
            last, ans = 0, 0
            
            while ptr < n:
                c = s[ptr]
                count = 0
                while ptr < n and s[ptr] == c:
                    ptr += 1
                    count += 1
                ans += min(count, last)
                last = count
            
            return ans
    

    ###C#

    public class Solution {
        public int CountBinarySubstrings(string s) {
            int ptr = 0, n = s.Length;
            int last = 0, ans = 0;
            
            while (ptr < n) {
                char c = s[ptr];
                int count = 0;
                while (ptr < n && s[ptr] == c) {
                    ptr++;
                    count++;
                }
                ans += Math.Min(count, last);
                last = count;
            }
            
            return ans;
        }
    }
    

    ###TypeScript

    function countBinarySubstrings(s: string): number {
        let ptr = 0, n = s.length;
        let last = 0, ans = 0;
        
        while (ptr < n) {
            const c = s[ptr];
            let count = 0;
            while (ptr < n && s[ptr] === c) {
                ptr++;
                count++;
            }
            ans += Math.min(count, last);
            last = count;
        }
        
        return ans;
    }
    

    ###Rust

    impl Solution {
        pub fn count_binary_substrings(s: String) -> i32 {
            let bytes = s.as_bytes();
            let n = bytes.len();
            let mut ptr = 0;
            let mut last = 0;
            let mut ans = 0;
            
            while ptr < n {
                let c = bytes[ptr];
                let mut count = 0;
                while ptr < n && bytes[ptr] == c {
                    ptr += 1;
                    count += 1;
                }
                ans += count.min(last);
                last = count;
            }
            
            ans
        }
    }
    

    复杂度分析

    • 时间复杂度:$O(n)$。
    • 空间复杂度:$O(1)$。

    O(1) 做法原理讲解(Python/Java/C++/C/Go/JS/Rust)

    作者 endlesscheng
    2026年2月18日 08:26

    为了做到 $\mathcal{O}(1)$ 时间,我们需要快速判断所有相邻比特位是否都不同

    如何判断不同?用哪个位运算最合适?

    异或运算最合适。对于单个比特的异或,如果两个数不同,那么结果是 $1$;如果两个数相同,那么结果是 $0$。

    如何对所有相邻比特位做异或运算?

    例如 $n = 10101$,可以把 $n$ 右移一位,得到 $01010$,再与 $10101$ 做异或运算,计算的就是相邻比特位的异或值了。

    如果异或结果全为 $1$,就说明所有相邻比特位都不同。

    如何判断一个二进制数全为 $1$?

    这相当于判断二进制数加一后,是否为 231. 2 的幂

    设 $x$ 为 (n >> 1) ^ n,如果 (x + 1) & x 等于 $0$,那么说明 $x$ 全为 $1$。

    class Solution:
        def hasAlternatingBits(self, n: int) -> bool:
            x = (n >> 1) ^ n
            return (x + 1) & x == 0
    
    class Solution {
        public boolean hasAlternatingBits(int n) {
            int x = (n >> 1) ^ n;
            return ((x + 1) & x) == 0;
        }
    }
    
    class Solution {
    public:
        bool hasAlternatingBits(int n) {
            uint32_t x = (n >> 1) ^ n;
            return ((x + 1) & x) == 0;
        }
    };
    
    bool hasAlternatingBits(int n) {
        uint32_t x = (n >> 1) ^ n;
        return ((x + 1) & x) == 0;
    }
    
    func hasAlternatingBits(n int) bool {
    x := n>>1 ^ n
    return (x+1)&x == 0
    }
    
    var hasAlternatingBits = function(n) {
        const x = (n >> 1) ^ n;
        return ((x + 1) & x) === 0;
    };
    
    impl Solution {
        pub fn has_alternating_bits(n: i32) -> bool {
            let x = (n >> 1) ^ n;
            (x + 1) & x == 0
        }
    }
    

    复杂度分析

    • 时间复杂度:$\mathcal{O}(1)$。
    • 空间复杂度:$\mathcal{O}(1)$。

    专题训练

    见下面位运算题单的「一、基础题」。

    分类题单

    如何科学刷题?

    1. 滑动窗口与双指针(定长/不定长/单序列/双序列/三指针/分组循环)
    2. 二分算法(二分答案/最小化最大值/最大化最小值/第K小)
    3. 单调栈(基础/矩形面积/贡献法/最小字典序)
    4. 网格图(DFS/BFS/综合应用)
    5. 位运算(基础/性质/拆位/试填/恒等式/思维)
    6. 图论算法(DFS/BFS/拓扑排序/基环树/最短路/最小生成树/网络流)
    7. 动态规划(入门/背包/划分/状态机/区间/状压/数位/数据结构优化/树形/博弈/概率期望)
    8. 常用数据结构(前缀和/差分/栈/队列/堆/字典树/并查集/树状数组/线段树)
    9. 数学算法(数论/组合/概率期望/博弈/计算几何/随机算法)
    10. 贪心与思维(基本贪心策略/反悔/区间/字典序/数学/思维/脑筋急转弯/构造)
    11. 链表、树与回溯(前后指针/快慢指针/DFS/BFS/直径/LCA)
    12. 字符串(KMP/Z函数/Manacher/字符串哈希/AC自动机/后缀数组/子序列自动机)

    我的题解精选(已分类)

    欢迎关注 B站@灵茶山艾府

    每日一题-交替位二进制数🟢

    2026年2月18日 00:00

    给定一个正整数,检查它的二进制表示是否总是 0、1 交替出现:换句话说,就是二进制表示中相邻两位的数字永不相同。

     

    示例 1:

    输入:n = 5
    输出:true
    解释:5 的二进制表示是:101
    

    示例 2:

    输入:n = 7
    输出:false
    解释:7 的二进制表示是:111.

    示例 3:

    输入:n = 11
    输出:false
    解释:11 的二进制表示是:1011.

     

    提示:

    • 1 <= n <= 231 - 1
    ❌
    ❌