Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
样例
Given num = 38.
The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return 2.
public class Solution {
public int addDigits(int num) {
//先将数字转化为字符串
String numStr = Integer.toString(num);
//当字符串长度为1时,说明已化道一个数字
while(numStr.length() > 1) {
//用sum来保存每次累加后的新数字
int sum = 0;
for(int i = 0; i < numStr.length(); i++) {
//利用API直接把每个字符代表的数字相加
sum = sum + Character.getNumericValue(numStr.charAt(i));
}
numStr = Integer.toString(sum);
}
return Integer.parseInt(numStr);
}
}