Payments app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-231bit-manipulation
A payments app reserves memory for each settlement batch in blocks. To keep the allocator fast, a block size is always a power of two: 1, 2, 4, 8 and so on.
Each batch asks for a number of entries, and the allocator rounds that up to the smallest block that fits. Your team lead asks: "How many entries does the allocator reserve for a day of batches?"
Write reserved_total(sizes).
sizes is the list of requests. Each request is a whole number of entries from 1 to 1,000,000,000.Input: sizes = [5, 8, 1, 100]
Output: 145The trick is to subtract 1, copy the top 1 bit into every position below it, and add 1. The table shows each request minus 1, the same number after the copying, and the block.
| Request | Request − 1 in binary | After copying the top bit down | Block |
|---|---|---|---|
| 5 | 100 | 111 | 8 |
| 8 | 111 | 111 | 8 |
| 1 | 0 | 0 | 1 |
| 100 | 1100011 | 1111111 | 128 |
Input: sizes = [1]
Output: 1A request of 1 is already a power of two, so its block is 1 and the total is 1.
Input: sizes = [536870913]
Output: 1073741824The request is one above 2^29, so the smallest block that fits is 2^30. The block is above 10^9, but it still fits in a 32-bit integer.
1 ≤ len(sizes) ≤ 700,0001 ≤ sizes[i] ≤ 1,000,000,000Trying each of up to 30 powers of two for every request costs about 30 × 700,000 = 21,000,000 steps, and a test over all 63 powers costs 44,100,000. Copying the top bit down takes 5 shifts for any size below 2^32, so the whole list costs about 3,500,000 steps.