二进制计数技巧:动态规划解法 LeetCode338给你一个整数n对于0 i n中的每个i计算其二进制表示中1的个数返回一个长度为n 1的数组ans作为答案。示例 1输入n 2输出[0,1,1]解释0 -- 01 -- 12 -- 10示例 2输入n 5输出[0,1,1,2,1,2]解释0 -- 01 -- 12 -- 103 -- 114 -- 1005 -- 101Python解法动态规划class Solution: def countBits(self, n: int) - List[int]: res [0] * (n 1) for i in range(1, n 1): res[i] res[i 1] (i 1) return resJava解法class Solution { public int[] countBits(int n) { int[] bits new int[n1]; for(int i 1; i n; i){ bits[i] bits[i 1] (i 1); } return bits; } }C解法#include vector using namespace std; class Solution { public: vectorint countBits(int n) { vectorint bits(n1,0); for(int i1;in;i){ bits[i] bits[i 1] (i 1); } return bits; } };关键句bits[i] bits[i 1] (i 1)逐项拆解(i 1)含义将数字i的二进制右移 1 位等价数学运算 (i // 2) 效果直接砍掉二进制最右侧的最后一位比特。 例(i5(101), i1 2(10))(bits[i 1])含义砍掉最后一位之后剩下高位部分里面「1 的个数」。高位序列没变里面所有 1 数量不变(i 1)按位与运算作用单独取出 i 二进制最末尾那一位如果 i 是奇数末尾 bit 1 → 结果 1如果 i 是偶数末尾 bit 0 → 结果 0