LC 338 - Counting Bits

Approach Need to couting bits for each n, and this is actually the number of bits for n/2 and plusing n%2. Code class Solution { public: vector<int> countBits(int n) { if(n == 0) return {0}; if(n == 1) return {0, 1}; vector<int> ans(n+1); ans[0] = 0; ans[1] = 1; for(int i = 2 ; i <= n ; ++i) { ans[i] = ans[i/2] + (i % 2); } return ans; } };

February 8, 2026 · 1 min

LC 2429 - Minimize XOR

[translate by ChatGPT] At first I didn’t fully understand the problem, but later I figured it out. We need to count how many 1’s are in the binary representation of num2, then find a number ans that has the same number of 1’s and minimizes the XOR value between num1 and ans. My initial idea was: after counting the number of set bits, match all the 1-bits in num1 first, and then fill the remaining bits starting from the smallest positions. ...

January 15, 2025 · 2 min