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.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
思路:将这个数字转化为string str,当str的长度等于1的时候也就是说明只有一位数的时候,就是结果了。
当str的长度不等于1的时候,把str每个位置的数字加起来再给str。
代码如下(已通过leetcode)
public class Solution {
public int addDigits(int num) {
String str=""+num;
int ans=0;
while(str.length()>1) {
for(int i=0;i<str.length();i++) {
ans+=str.charAt(i)-'0';
}
str=""+ans;
ans=0;
}
return Integer.parseInt(str);
}
}