心得:
題目要求將每一位數相加,直到剩下個位數。
問題:
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.
答案:
- For + 遞迴
12345678910111213141516171819public 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);}}} - LinQ + 遞迴
12345678910111213public class Solution {public int AddDigits(int num) {string str = num.ToString();if (str.Length < 2){return int.Parse(str);}else{return AddDigits(str.Sum(x => int.Parse(x.ToString())));}}} - Normal
1234567891011121314151617public 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);}}