Roundabout Rounding is a good example of replacing simulation with a digit pattern. Instead of testing every number up to N, the solution counts ranges where two rounding methods disagree.
The pattern to notice
The disagreement happens in ranges controlled by digit thresholds. For a fixed number of digits, the lower edge is made of repeated 4s and the upper edge is just below a 5 followed by zeros.
| Digits | Lower pattern | Upper pattern |
|---|---|---|
| 1 | 4 | 4 |
| 2 | 44 | 49 |
| 3 | 444 | 499 |
Once the range is known, counting is just arithmetic.
answer += max(0, min(N, upper) - lower)
Why this is faster
If N can be huge, checking each number is too slow. But the number of digit lengths is small. Counting by digit length turns the work into a handful of range calculations.
Common mistakes
- Looping through every number instead of counting ranges.
- Forgetting to cap the upper bound at
N. - Getting off by one at the lower or upper threshold.
- Using string construction without checking the numeric meaning of the range.
Practice prompt
Find the disagreement ranges for 1-digit, 2-digit, and 3-digit numbers. Then count how many numbers up to N = 120 fall in those ranges.
