+ 1

Can somene explain more about sum of digit instead of just adding them? It really helps me alot !

Deep understanding sum of digit.

13th Feb 2019, 10:10 PM
Alvin Aw Eng Chien
Alvin Aw Eng Chien - avatar
2 Antworten
+ 2
Is there really something that deep about the sum of digits? Here is how this goes: Let's say you have a number: 123 To acces the last digit of the number, you use the modulo operator, it should look like this: int lastDigit = 123%10 Now in lastDigit, the remainder of 123/10 is stored, which is 3. What about the second digit? Well, same principle, but we cut down the last digit, because we dont need it, by dividing by 10 and keeping the integer part. secondDigit = 123/10%10 ,so now secondDigit stores 2 To get the third digit, you cut down 2 digits, by dividing by 100, and so on and so forth. However, what if you dont know how many digits the number has? No problem, you use a while loop and you keep dividing until you hit 0 This applies to all languages similar to C and more: int n = 123; int sum=0,c; do{ c = n%10; sum = sum + c; n = n /10; }while(n!=0); print(sum); Keep in mind that n is now 0, so it lost the initial value of 123. You can get around this by making a copy of n, and using that instead
13th Feb 2019, 10:30 PM
Demon
Demon - avatar
0
Or do you mean stuff like this: if the sum of digits = 9, number is divisible by 9 e.g. 27(2+7 = 9) is divisible by 9 (27/9 = 3)? https://en.m.wikipedia.org/wiki/Digit_sum http://www.sjsu.edu/faculty/watkins/Digitsum.htm
14th Feb 2019, 1:36 AM
Denise Roßberg
Denise Roßberg - avatar