Solved an interesting problem today on Codeforces: Call of Soldiers 3.
At first, the problem looked pretty straightforward. We had to compare Fedor's army with the armies of other players and count how many players differed in at most k types of soldiers.
Initially, I tried comparing the bits manually using bitwise AND (&) and right shifts. However, I made a small operator precedence mistake. I forgot to put parentheses around the bitwise AND operations before comparing them with !=. It was a simple mistake, but it reminded me how important operator precedence is in C++.
After thinking about it again, I realized that XOR (^) makes this problem much simpler. XOR gives 1 at positions where two numbers have different bits. So, all I needed was to count the set bits in the XOR result.
I used __builtin_popcount() to make the implementation shorter and cleaner.
Key takeaway: Sometimes, knowing the right bitwise operator can save you from writing unnecessary code. Also, a small operator precedence mistake can change the entire logic!
Another small lesson learned today. On to the next problem!
=> View my Codeforces solution — https://codeforces.me/contest/467/submission/399102777



