Home > Back-end >  My java program will not return the correct value?
My java program will not return the correct value?

Time:11-12

I have written a java program that finds the recursive sum of the digits of a number.

It prints the correct value in the line right before the return statement, but still returns the wrong value.

public class DRoot {
  public static int digital_root(int n) {
    //going to solve using recursion
    System.out.println(n   " before if and for loop");
    String temporary = Integer.toString(n);
    int tempInteger = n;
    System.out.println(temporary.length()   " is temporary length");
    if(temporary.length() == 1){
      System.out.println("returns at beginning");
      System.out.println("n before return is: "   n);
      return tempInteger;
    }
    n = 0;
    if(temporary.length() != 1){
      for(int i = 0; i < temporary.length(); i   ){
        n  = Integer.parseInt(temporary.substring(i, i 1));
        System.out.println(n   " during if and for loop");
      }
    } else {
      System.out.println("returns after for loop");
      return n;
    }
    //calls the digital_root method recursively
    digital_root(n);
    return n;
  }
}

CodePudding user response:

Your code could have been much shorter and simpler.

Based on your attempts, perhaps it would be best to represent the number as a String.

At each step of the recursion, take the first digit and add it to the sum of the remaining sub-string. Once you run out of digits, you stop.

Something like this:

public class DRoot {
    public static int recursiveDigitSum(String n) {
        if (n.length() == 0) {
            return 0;
        }
        return n.charAt(0) - '0'   recursiveDigitSum(n.substring(1));
    }
  
    public static void main(String[] args) {
        System.out.println(recursiveDigitSum("51")); // outputs 6
    }
}

CodePudding user response:

The result of your recursive call is lost. Maybe what you want is:

n = digital_root(n);
return n;
  •  Tags:  
  • java
  • Related