优化 N 的位数和
Optimize the Sum of Digits of N
Codewars 问题:(数字总和/数字根)
给定n,求n的各位数字之和。如果该值超过一位数,则继续以这种方式减少,直到生成一位数。输入将是一个非负整数。
测试用例:
16 --> 1 + 6 = 7
942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6
132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6
493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
我的代码:
#include <bits/stdc++.h>
using namespace std;
int singleDigit(int n)
{
int ans;
while (n > 0)
{
int lastDigit = n % 10;
n /= 10;
ans += lastDigit;
}
while (ans > 9)
{
int n1 = ans;
ans = 0;
while (n1 > 0)
{
int lastDigit = n1 % 10;
n1 /= 10;
ans += lastDigit;
}
}
return ans;
}
int main()
{
cout << singleDigit(49319366) << endl;
return 0;
}
是否有更好或优化的方法来解决这个问题或降低时间复杂度?
此函数适用于非负整数,适用于负数很简单。
int singleDigit(int n)
{
return (n-1) % 9 + 1;
}
具有以下优点:
- 没有要忘记初始化的变量
- 没有循环来提交差一错误
- 快
缺点是:
- 目前还不清楚它是如何工作的或为什么工作
有关最后一个要点的更多信息,请参阅:
- Direct formulas for the digital root
- Modulo operation with negative numbers
Codewars 问题:(数字总和/数字根)
给定n,求n的各位数字之和。如果该值超过一位数,则继续以这种方式减少,直到生成一位数。输入将是一个非负整数。
测试用例:
16 --> 1 + 6 = 7
942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6
132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6
493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
我的代码:
#include <bits/stdc++.h>
using namespace std;
int singleDigit(int n)
{
int ans;
while (n > 0)
{
int lastDigit = n % 10;
n /= 10;
ans += lastDigit;
}
while (ans > 9)
{
int n1 = ans;
ans = 0;
while (n1 > 0)
{
int lastDigit = n1 % 10;
n1 /= 10;
ans += lastDigit;
}
}
return ans;
}
int main()
{
cout << singleDigit(49319366) << endl;
return 0;
}
是否有更好或优化的方法来解决这个问题或降低时间复杂度?
此函数适用于非负整数,适用于负数很简单。
int singleDigit(int n)
{
return (n-1) % 9 + 1;
}
具有以下优点:
- 没有要忘记初始化的变量
- 没有循环来提交差一错误
- 快
缺点是:
- 目前还不清楚它是如何工作的或为什么工作
有关最后一个要点的更多信息,请参阅:
- Direct formulas for the digital root
- Modulo operation with negative numbers