[C#][LeetCode][Easy] 258. Add Digits

心得:

題目要求將每一位數相加,直到剩下個位數。

問題:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
答案:

1
2
3


1. For + 遞迴

public class Solution {
public int AddDigits(int num) {
string str = num.ToString();
if (str.Length < 2)
{
return int.Parse(str);
}
else
{
int tmp = 0;
for (int i = 0; i < str.Length; i++)
{
tmp += int.Parse(str[i].ToString());
}

        return AddDigits(tmp);
    }
}

}

1
2


  1. LinQ + 遞迴
1
2
3
4
5
6
7
8
9
10
11
12
13
14

public class Solution {
public int AddDigits(int num) {
string str = num.ToString();
if (str.Length &lt; 2)
{
return int.Parse(str);
}
else
{
return AddDigits(str.Sum(x =&gt; int.Parse(x.ToString())));
}
}
}
1
2
3


3. Normal

public class Solution {
public int AddDigits(int num) {
string str = num.ToString();
while (str.Length > 1)
{
int tmp = 0;
for (int i = 0; i < str.Length; i++)
{
tmp += int.Parse(str[i].ToString());
}

        str = tmp.ToString();
    }

    return int.Parse(str);
}

}

`