Recursive sum to find single digit

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 798
I have a number as N=2345

If I sum them the result will be 2+3+4+5 =14;

If I further sum them it will be 1+4 = 5; which is a single digit;

How to do this?

public static int FindSingleDigit(int N)
{
var sum = 0;
int count = 0;
while (N != 0)
{
sum = sum + (N % 10);
N = N / 10;
count++;
}
if (sum >= 10) return FindSingleDigit(sum);
else return sum;
}


Invoke it as

var result = FindSingleDigit(2345);

Comments or Responses

Posted by: Saranpselvam on: 5/12/2014 Level:Starter | Status: [Member] | Points: 10
Good

Login to post response