[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. 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);
            }
        }
    }
  2. LinQ + 遞迴
    public 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())));
            }
        }
    }
  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);
        }
    }


這裡的資訊對您有用嗎?歡迎斗內給我