leetcode [#258]

目录

题目

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
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public int addDigits(int num) {
int result;
if (num < 10) {
result = num;
} else {
String num2str = Integer.toString(num);
int newNum = 0;
for(int k = 0; k< num2str.length(); k++){
newNum += Integer.parseInt(String.valueOf(num2str.charAt(k)));
}
result = addDigits(newNum);
}
return result;
}
}

注意事项

  判断数字是否小于10(即是否是1位的数字),如果不是,将数字转为字符串,遍历取出每个字符,再转为对应数字,求和后用得到的结果递归调用addDigits()方法。