直接法
int all_sum(int n)
{
int sum = 0;
while (n)
{
sum += (n % 10);
n /= 10;
}
return sum;
}
int main()
{
int n = 1234;
cout << all_sum(n) << endl;
return 0;
}
递归法
int all_sum(int n)
{
if (n > 9)
return all_sum(n / 10) + n % 10;
else
return n;
}
int main()
{
int n = 1234;
cout << all_sum(n) << endl;
return 0;
}