Summing a number’s digits programming exercise.
Pythia, Oracle of Delphi, wants to do some numerology. She promises to Pray for Apollos favor to this who:
Write a function which takes a number as input and returns the sum the absolute value of its digits.
Еxample: Input: 12 -> 1+2 = 3 output: 3 52 -> 5+2 = 7 output: 7 -78 -> 7+8 = 15 output: 15
Scroll down to see the solution of this math…I mean coding problem.
public static int SumDigits(int n) { //first we need to get the absolute value of the number //the Abs() in Math in c# does exactly that. //not that we cant use a simple IF but //Math.Abs() is more readable n = Math.Abs(n); //Lets get the digits of the number //and in the same time sum them int sum = 0; //lets see how to get the last digit of the number 123 ? //well will use the reminder operator //123%10 = 3 //and then the second one ? //123 / 10 =12 //12%2 =2 //and so one until we have no digits left. while (n != 0) { sum += n % 10; n /= 10; } return sum;/*
* If you are not familiar with this small algorithm for taking
* the digits of a number, experiment a little with it.
* Make a small function that takes any integer and return
* a char array with its digits. Also its good for showing off in
* job interviews ;)
*/
}