write a program int i=123 calculate sum=1=2=3 optimized solution


write a program int i=123 calculate sum=1=2=3 optimized solution

q: How to sum individual digits of integer?

I have an integer value (ex: 723) and i want to add up all the values in this integer until i get a single value.


ex: 7 + 2 + 3 = 12
    1 + 2     = 3


Ans


int i = 723;
int acc;
do {
    acc = 0;
    while (i > 0)
    {
        acc += i % 10;
        i /= 10;
    }
    i = acc;
} while(acc>=10);
% 10 gives the final digit each time, so we add that into an accumulator. /= 10 performs integer division, essentially removing the final digit each time. Then we repeat until we have a small enough number.
---------------------------------------------------------------------------------


hint....
Using conversion from int to string and back probably isn't that fast. I would use the following
public static int[] ToDigitArray(int i)
{
    List<int> result = new List<int>();
    while (i != 0)
    {
        result.Add(i % 10);
        i /= 10;
    }
    return result.Reverse().ToArray();
}

Comments