Problem overview
The function sumUntilLimit receives a positive integer limit. It adds the numbers 1, 2, 3 and so on, in that order, and stops as soon as the total is at least limit. It returns how many numbers it added. The last number counts even if it pushes the total past the limit.
For limit = 10, the sum 1 + 2 + 3 + 4 reaches exactly 10, so the answer is 4. For limit = 11, the total after four numbers is 10, which is still below 11, so 5 is added as well. The total becomes 15 and the answer is 5. For limit = 1, the first number already reaches the limit, so the answer is 1.
Approach
Keep two variables: total, the sum so far, and count, how many numbers have been added. Because the numbers go 1, 2, 3 in order, count is also the last number added. So each turn does two things: move count to the next number, then add it to total.
The loop runs while total < limit. As soon as total reaches or passes limit, the condition is false and the loop stops, which is exactly when the adding must stop. Here is the run for limit = 11:
| count | total |
|---|---|
| 1 | 1 |
| 2 | 3 |
| 3 | 6 |
| 4 | 10 |
| 5 | 15 |
After the fifth row, 15 is not less than 11, so the loop ends and the function returns 5.
Step by step
- Create
var total = 0. It is avarbecause it grows inside the loop. - Create
var count = 0. No number has been added yet. - Loop while
total < limit. - Add 1 to
countwith+= 1. It is now the next number to add: 1 on the first pass, 2 on the second. - Add
counttototal. The order matters:countgoes up first, so the number added is the right one. - Return
countafter the loop.
The solution in Swift
class Solution {
func sumUntilLimit(_ limit: Int) -> Int {
var total = 0
var count = 0
while total < limit {
count += 1
total += count
}
return count
}
}
Swift details worth knowing:
- No
++. Swift has no increment operator, so counters grow with+= 1. - Parameters are constants. The loop never changes
limit, so no copy is needed here. The two variables hold the state that changes. - The limit is read each time.
while total < limitis checked before every pass, including the first. With a positivelimit, the first check is always true, becausetotalstarts at 0. - Size.
Intis 64 bits, and the total never goes much past the limit, so there is no overflow.
Edge cases and common mistakes
- Reaching the limit exactly.
limit = 10stops whentotalis 10. The loop condition uses<, so a total equal to the limit ends the loop. Using<=would add one more number and return 5. - Small limits.
limit = 1gives 1,limit = 2gives 2 (1 + 2 = 3) andlimit = 3gives 2 (1 + 2 = 3). - Adding before incrementing. If
total += countcame first, the first pass would add 0, and the numbers added would trail one behind. - Returning
total. The question asks how many numbers were added, not their sum. - Large limits.
limit = 1000000000needs 44721 passes, which is quick.
Testing
10gives 4.11gives 5.1gives 1.2gives 2.3gives 2.1000000000gives 44721.
