Java 如何编写递归方法来返回整数中的数字总和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9696853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:17:21  来源:igfitidea点击:

How to write a recursive method to return the sum of digits in an int?

javarecursion

提问by user1268088

So this is my code so far.

所以这是我到目前为止的代码。

    public int getsum (int n){
        int num = 23456;
        int total = 0;
        while (num != 0) {
            total += num % 10;
            num /= 10;
        }
    } 

The problem is that i cant/know how to change this into a recursive method Im kind of new with recursion and i need some help on implementing this method to change it so its recursive.

问题是我不能/不知道如何将其更改为递归方法我对递归有点陌生,我需要一些帮助来实现此方法以将其更改为递归。

回答by Rahul Borkar

Here it is,

这里是,

//sumDigits function
int sumDigits(int n, int sum) {    
    // Basic Case to stop the recursion
if (n== 0)  {
        return sum;
    } else {
        sum = sum + n % 10;  //recursive variable to keep the digits sum
        n= n/10;
        return sumDigits(n, sum); //returning sum to print it.
    }
}

An example of the function in action:

运行中的函数示例:

public static void main(String[] args) {
     int sum = sumDigits(121212, 0);
     System.out.println(sum);
}

回答by me_digvijay

Try this:

尝试这个:

int getSum(int num)
{
    total = total + num % 10;
    num = num/10;
    if(num == 0)
    {
        return total;
    } else {
        return getSum(num);
    }
}

回答by Naytzyrhc

Short, recursive and does the job:

简短,递归并完成工作:

int getsum(int n) {
   return n == 0 ? 0 : n % 10 + getsum(n/10);
}

回答by Silver

int getSum(int N)
{
    int totalN = 0;

    totalN += (N% 10);
    N/= 10;

    if(N == 0)
        return totalN;
    else 
        return getSum(N) + totalN;
}

回答by JerryFZhang

public static int digitSum (int n)
  { 
    int r = n%10;       //remainder, last digit of the number
    int num = n/10;     //the rest of the number without the last digit
    if(num == 0)
    {
      return n;
    } else {
      return digitSum (num) + r;
    }} 

回答by TheArchon

This works for positive numbers.

这适用于正数。

public int sumDigits(int n) {
  int sum = 0;
  if(n == 0){
  return 0;
  }
  sum += n % 10; //add the sum
  n /= 10; //keep cutting
  return sum + sumDigits(n); //append sum to recursive call
}

回答by nas

#include <iostream>
int useRecursion(int x);
using namespace std;

int main(){
    int n;
    cout<<"enter an integer: ";
    cin>>n;
    cout<<useRecursion(n)<<endl;
    return 0;
}

int useRecursion(int x){
    if(x/10 == 0)
        return x;
    else
        return useRecursion(x/10) + useRecursion(x%10);
}

回答by Samuel

    import java.util.Scanner;
public class Adder {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        System.out.println();
        int number = input.nextInt();
        System.out.println("The sum of the digits is " +adder(number));

    }
    public static int adder(int num){
        int length = String.valueOf(num).length();
        int first , last , sum;
        if (length==1){
            return num;
        }
        else
        {
            first = num /10;
            last = num % 10;
            sum = last + adder(first);
        }
        return sum;
    }
}

回答by Dimuthu Maduranga

public static int sumOfDigit(int num){
    int sum=0;
    if (num == 0)
    return sum;
            sum = num%10 + sumOfDigit(num/10);
    return sum;
}
public static void main(String args[]) {
    Scanner input=new Scanner(System.in);
    System.out.print("Input num : ");
    int num=input.nextInt();
    int s=sumOfDigit(num);
    System.out.println("Sum = "+s);
}

}

}

回答by parsecer

I think it's the shortest so far. The input thing is up too you, though.

我认为这是迄今为止最短的。不过,输入也取决于你。

 public static int getSum(int input)  {  //example: input=246
       int sum=0;   
       if (input%10==input)  { //246%10=6;  
              return input%10; //2%10=2
       }

       return input%10+getSum((input-input%10)/10); //(246-6)/10=24; 24%10=4
 }