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

前端 未结 12 1349
说谎
说谎 2020-12-06 14:34

So this is my code so far.

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


        
相关标签:
12条回答
  • 2020-12-06 15:23

    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
     }
    
    0 讨论(0)
  • 2020-12-06 15:25

    Try this:

    int getSum(int num)
    {
        total = total + num % 10;
        num = num/10;
        if(num == 0)
        {
            return total;
        } else {
            return getSum(num);
        }
    }
    
    0 讨论(0)
  • 2020-12-06 15:28
    int getSum(int N)
    {
        int totalN = 0;
    
        totalN += (N% 10);
        N/= 10;
    
        if(N == 0)
            return totalN;
        else 
            return getSum(N) + totalN;
    }
    
    0 讨论(0)
  • 2020-12-06 15:29

    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);
    }
    
    0 讨论(0)
  • 2020-12-06 15:29
    #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);
    }
    
    0 讨论(0)
  • 2020-12-06 15:30
    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;
        }} 
    
    0 讨论(0)
提交回复
热议问题