I solved it after looking up StackOverflow for examples around the modulus or remainder (%). I copied code, changed it to mine, and solved the puzzle, but now I still don't how this works EXACTLY.
int sum = 0;
while (number > 0) {
sum = sum + number % 10;
number = number / 10;
}
return sum;
Can someone in plain English explain what this code does, step by step? It seems rather important, so I actually want to understand what I'm doing, instead of just copying stuff of the internet.
I solved the puzzle, but still don't know HOW it actually works.
Under discussion
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
NNAMDI HENRY
30 June 2021, 11:40
I am stuck at this point,
I don't even understand the question.
but can any one assist me please.
much appreciation.
0
Nouser
12 January 2021, 11:40
number modulo 10 returns the remainder of a division / 10. Means if you divide 123 / 10 you get 12, the remainder is 3. If you now divide that number by 10 (to get rid of the last digit), you get 12 and again can do a modulo operation on that 12. 12 & 10 wil give you the remainder 2, add that to the 3 of the previous iteration and divide the 12 / 10... and so on.
0
J H U X
13 January 2021, 06:43
Thank you for that, but I'm still having a bit of trouble following the code when I do the math myself. Let's take the example from the task: 546.
while (number > 0) {
sum = sum + number % 10;
number = number / 10; }
becomes
while (546 > 0) {
6 = 0 + 546%10;
54,6 = 546 / 10; }
then becomes
while (54,6 > 0) {
4,6 = 0 + 54,6%10;
5,46 = 54,6 / 10; }
then becomes
while (5,46 > 0) {
0 = 0 + 5,46%10;
0,546 = 5,46 / 10; }
After that, the sum will keep answering 0. So I get 10,6 as when I return sum when I calculate it myself, but when Java does it, the answer is 15? I know my math is wrong, but where exactly?
0
Nouser
13 January 2021, 11:29
that's all int math here therefore you have the remainder but no decimal places
while (54 > 0) {
10 = 6 + 54 % 10;
5 = 54 / 10; }
while (5 > 0) {
15 = 10 + 5 %10;
0 = 5 / 10; }
whilw (0 > 0) //false
0
J H U X
14 January 2021, 12:21
Thank you for your explanation. I've calculated it with a couple of other examples and practised it a bit. It makes sense when you ignore the decimals, indeed.
0