1
2
3
|
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
|
public
class
Solution {
public
int
addDigits(
int
num) {
////循环和递归解决~
int
sum=
0
;
if
(num/
10
==
0
)
return
num;
while
(num!=
0
){
sum=sum+num%
10
;
num=num/
10
;
}
// System.out.println(sum);
return
addDigits(sum);
}
}
|
PS:额,直接循环加递归解决。。。。
进阶:不使用循环和递归。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1890563