leetcode258. 各位相加
没想到我现在能卡在这样的题目上
只尝试了循环模拟,一开始代码是这样的。
class Solution {
public int addDigits(int num) {
int temp;
do {
while(num != 0) {
temp += num % 10;
num = num / 10;
}
num = temp;
} while(temp / 10 != 0);
return temp;
}
}
主打的就是一个神智不清,题目要求得出最后个位数的答案,我却不知道在算什么。 debug了很久之后改出来了
class Solution {
public int addDigits(int num) {
int temp;
do {
temp = 0;
while(num != 0) {
temp += num % 10;
num = num / 10;
}
num = temp;
} while(temp / 10 != 0);
return temp;
}
}
发现题解里面有递归做法,现在居然要花很久才能理解,要反复看了。
class Solution {
public int addDigits(int num) {
if(num < 10) {
return num;
}
int temp = 0;
while(num != 0) {
temp += num % 10;
num /= 10;
}
return addDigits(temp);
}
}