Course / The terminal and the language
Add up a number's digits
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach lab: download it, edit the file named in the instructions, then submit.
gonomicon fetch week-1/11-04-digit-sum
cd 11-04-digit-sum
gonomicon submitGoal
Sum the individual digits of a positive integer N, using a condition-only for loop with % and /.
Example
If you needed to sum the digits of 203, the loop would peel off 3, then 0, then 2:
sum := 0
n := 203
for n > 0 {
sum += n % 10
n /= 10
}
// sum is now 5
Rules
- Edit
digitsum.go.DigitSumhas a// TODOcomment and a return line you will change. - Copy
Ninto a local variable first; don't changeNitself. - Use a condition-only
forloop (just a keep-going question, no init or post part) that runs while that local variable is greater than0. - On each pass, add the last digit with
% 10to a running sum, then remove that digit with/= 10. Ncan be0, in which case the loop never runs and the sum stays0.- Do not change
var N intor theDigitSumfunction signature. Do not add imports.
What you'll practice
Writing a condition-only for loop, and peeling digits off a number with % and /.
Run it
gonomicon fetch week-1/11-04-digit-sum
cd 11-04-digit-sum
gonomicon test
gonomicon submit
Hints
- Copy N into a local variable so you don't change N itself, then use a condition-only for loop that keeps going while that local variable is above 0.
- On each pass, add the last digit (n % 10) to your total, then drop that digit with integer division (n /= 10).
- sum := 0 n := N for n > 0 { sum += n % 10 n /= 10 } return sum