[英]How do I create a recursive function that sums up digits?
I need to create a function that recursively adds up each digit in a large number.我需要创建一个函数,以递归方式将大量数字的每个数字相加。
For example, if the user inputs the number 143
, the function should return 1+4+3
which is 8
.例如,如果用户输入数字
143
,则函数应返回1+4+3
,即8
。
How can I do this?我怎样才能做到这一点?
The idea is that given a number, you can sum its digits by recursively summing the number without its last digit sum, and add the last digit.这个想法是,给定一个数字,您可以通过递归求和没有最后一位数字总和的数字来求和它的数字,然后添加最后一位数字。 Calculating the last digit is simple
x%10
, and getting the number without the last digit is x/10
.计算最后一位很简单
x%10
,得到没有最后一位的数字是x/10
。 The base case when you hit 0 (you removed all digits) - return 0.当您点击 0(您删除所有数字)时的基本情况 - 返回 0。
int sum_digits(int x) {
if (x == 0)
return 0;
return x%10 + sum_digits(x/10);
}
You basically just need to calculate %10 every time to get the last digit and recursively sum up all those results.您基本上只需要每次计算 %10 即可获得最后一位数字并递归地总结所有这些结果。
Here is an example:下面是一个例子:
int sum;
public int sumOfDigits(int number){
if(number<10)
return sum+number;
else{
sum += (number%10);
return sumOfDigits(number/10);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.