60、各位相加
题目描述
PS:你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
不看PS的要求:
直接撸出代码:
class Solution {
public int addDigits(int num) {
int x = 0;
while (true) {
x = 0;
while (num > 0) {
x += num%10;
num /=10;
}
num = x;
if(x <= 9){
break;
}
}
return x;
}
}
那肯定效率很低
之后进行优化
看到O(1)就知道这道题有公式解:
根据这个博客来简单了解一下思路 https://blog.****.net/reuxfhc/article/details/80226547
将代码撸出来:
注释的是上面的循环解法
public static int addDigits(int num) {
if(num == 0){
return 0;
}
return (num-1) % 9 +1;
/*int x = 0;
if(num <= 9){
return num;
}
while (true) {
x = 0;
while (num > 0) {
x += num%10;
num /=10;
}
num = x;
if(x <= 9){
break;
}
}
return x;*/
}
再次验证数学对于计算机的推进作用