[Codewars]Sum of Digits / Digital Root

每個位數拆開相加等於多少?

In this kata, you must create a digital root function.

A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

Example:

digital_root(16)
=> 1 + 6
=> 7

digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6

digital_root(132189)
=> 1 + 3 + 2 + 1 + 8 + 9
=> 24 ...
=> 2 + 4
=> 6

digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2

第一次的寫法就是 把input當作字串一個一個拆開來相加

用遞迴做到長度等於1為止

Solution1:

using System;
public class Number
{
    public int DigitalRoot(long n)
    {
        string s = n.ToString();
        long a = 0;
        if (s.Length == 1)
            return Int32.Parse(s);
        for (int i = 0; i < s.Length; i++)
        {
            a += Int32.Parse(s[i].ToString());
        }
        return DigitalRoot(a);
    }
}

很好 完美!

送出答案後看別人的寫法差點吐血

原來還可以這樣寫    我跪了...

Solution2:

public class Number
{
    public int DigitalRoot(long n)
    {
       return (int)(1+(n-1)%9);
    }
}

 

Reference

https://en.wikipedia.org/wiki/Digital_root