Payments app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1342bit-manipulation
A payments app splits each payout with a fixed rule. While the amount is greater than 0, an even amount is halved, so that two accounts can share it. An odd amount has 1 unit set aside as a fee, and the rest is left.
Your team lead wants to know the load of a day: how many halvings and how many set-aside units the rule makes over all payouts.
Write payout_steps(payouts).
Input: payouts = [10, 1, 6]
Output: [5, 5]The payout 10 takes 5 steps: 3 halvings and 2 set-asides. The payout 1 takes one set-aside. The payout 6 takes 4 steps: 2 halvings and 2 set-asides.
| Payout | Steps in order | Halvings | Set-asides |
|---|---|---|---|
| 10 | 10 → 5 (halve), 5 → 4 (set aside), 4 → 2 (halve), 2 → 1 (halve), 1 → 0 (set aside) | 3 | 2 |
| 1 | 1 → 0 (set aside) | 0 | 1 |
| 6 | 6 → 3 (halve), 3 → 2 (set aside), 2 → 1 (halve), 1 → 0 (set aside) | 2 | 2 |
The totals are 5 halvings and 5 set-asides.
Input: payouts = [1]
Output: [0, 1]A payout of 1 is odd, so one unit is set aside and the amount is 0. There is no halving.
Input: payouts = [8]
Output: [3, 1]The payout 8 halves to 4, 2 and 1: three halvings. Then 1 is odd: one set-aside.
1 ≤ length of payouts ≤ 10^61 ≤ payouts[i] ≤ 10^9A payout up to 10^9 has at most 30 binary digits, and each digit costs one or two steps, so it needs up to 59 steps. Playing the rule out for 10^6 payouts costs up to about 6 x 10^7 steps, which is slow in some languages.
The totals stay below 6 x 10^7, so a 32-bit integer is enough.