All problems
0754MediumArrayMathBit Manipulation

Differing Flag Bits Across Registers

Tracked in this browser only
Write code

Trains the technique from

LeetCode 477Total Hamming Distance

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Every unit on a shop floor publishes its state as one non-negative integer whose binary digits act as independent flags. Line up the binary forms of two states, padding the shorter one with leading zeros so both have the same width. Their disagreement is how many bit positions hold a 1 in exactly one of the two states.

You are handed registers, the current state of each unit in reporting order. Add up the disagreement of every unordered pair of two different positions in registers and return that total. Two units holding the same state still form a pair; their disagreement is 0.

A list with a single unit has no pairs at all.

Examples

Example 1

Input
registers = [6, 11, 20, 3]
Output
17

Written to five bit positions the four states are 00110, 01011, 10100 and 00011. The six pairs disagree in 3, 2, 2, 5, 1 and 4 positions respectively, and those add up to the returned total.

Example 2

Input
registers = [9, 9, 24]
Output
4

The first two states are identical, so that pair disagrees nowhere. State 9 is 01001 and state 24 is 11000, which disagree in 2 positions, and that pair occurs twice.

Example 3

Input
registers = [7, 7, 7, 7]
Output
0

All four units publish the same state, so every one of the six pairs disagrees nowhere.

Constraints

  • 1 <= registers.length <= 10^4
  • 0 <= registers[i] <= 10^9
  • Under these bounds the returned total is at most 10^9.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def total_flag_disagreement(registers: list[int]) -> int:
Java
public int totalFlagDisagreement(int[] registers)
September 7
Apply