LeetCode -- 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.
就是給定一個數字n,將每一位相加,再判斷和是否只有一位:
只有1位:返回這個和
否則:繼續相加每一位,判斷新的和
實現代碼:
public class Solution {
public int AddDigits(int num) {
if(num < 10){
return num;
}
var n = num;
while(true){
var s = 0;
while(n >= 10){
s+= n % 10;
n /= 10;
}
s += n;
if(s < 10){
return s;
}
n = s;
}
}
}