Pls explain this code block. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Pls explain this code block.

var a = 423; var sum = 0; while(a >0){ sum += a % 10; a = Math.round(a/10); } console.log(sum);

16th Apr 2018, 11:51 PM
🄼🄼🄷🄺
🄼🄼🄷🄺 - avatar
2 Answers
+ 2
This block of code sums the individual integers in a number. For this example, that is 3 + 2 + 4. Every time through the loop sum is added to itself plus the remainder of a divides by 10. 423 % 10 = 3 Then a becomes itself divided by 10, and actually this should be: Math.floor(a / 10) because if the number was 426, it would round 42.6 to 43. So now a becomes 42. 42 % 10 is 2, sum = 3 + 2 = 5, and a becomes floor(4.2) which is 4. 4 % 10 is 4, sum = 5 + 4 = 9, and then floor (0.4) is zero and then the loop breaks.
17th Apr 2018, 12:08 AM
Zeke Williams
Zeke Williams - avatar
0
Here! It is pretty detailed. Go straight to the JS tab and read the comments. Like Jay said, they are just getting and adding the digits of the number https://code.sololearn.com/WMZa2aZdGP6n/?ref=app
17th Apr 2018, 12:15 AM
cyk
cyk - avatar