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.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
题意:
给定一个整数,求其各位之和,直到只剩下一位数
算法思路:
循环相加直到小于10即可
代码:
package easy;
/*
@author wchstrife
@version 2017年7月22日下午11:03:12
*/
public class AddDigits {
public int addDigits(int num) {
while(num >9){
num = num/10 + num%10;
}
return num;
}
}