Online store~25 min2s · 256 MBtarget O(32 × n) time, O(1) spaceclassic twin: lc-371bit-manipulation
A handheld stock scanner adds each batch it scans to a running counter. Its firmware has no addition instruction. It adds with AND, XOR and shifts, and the counter is a 32-bit register, so it wraps around when it passes 2,147,483,647.
The firmware team wants to know what the register shows after a day of batches. Your team lead asks: "What number does the register hold at the end, read as a signed 32-bit value?"
Write register_total(counts).
counts is the list of batch sizes, in the order they were scanned. The register starts at 0.Input: counts = [5, 7, 9]
Output: 21Adding two numbers without + repeats two steps. XOR gives the sum without carries, and AND shifted left by one gives the carries. Repeat until no carry is left. The table adds 5 and 7, the first two batches.
| Round | a | b | Carry (a & b) << 1 |
New a a ^ b |
|---|---|---|---|---|
| 1 | 5 (0101) | 7 (0111) | 10 (1010) | 2 (0010) |
| 2 | 2 (0010) | 10 (1010) | 4 (0100) | 8 (1000) |
| 3 | 8 (1000) | 4 (0100) | 0 (0000) | 12 (1100) |
The register shows 12 after the first two batches, and adding 9 gives 21.
Input: counts = [2147483647, 1]
Output: -2147483648The largest 32-bit value plus 1 wraps around to the smallest.
Input: counts = [0]
Output: 0A register that starts at 0 and adds a batch of 0 stays at 0.
1 ≤ len(counts) ≤ 500,0000 ≤ counts[i] ≤ 2,147,483,647An adder that goes through all 32 bit positions for every batch costs 16,000,000 steps for 500,000 batches. The carry loop stops as soon as no carry is left. That takes a few rounds for typical numbers, and at most 32 for any numbers.