Advertisement
brilliant_moves

RecursiveDigitAdder.java

Jul 30th, 2015
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.17 KB | None | 0 0
  1. import java.util.Scanner; // to read data
  2.  
  3. public class RecursiveDigitAdder {
  4.    
  5.    /**
  6.    *    Program:    RecursiveDigitAdder.java
  7.    *    Purpose:    Keep adding sum of digits until sum <= 9
  8.    *    Creator:    Chris Clarke
  9.    *    Created:    17.12.2012
  10.    */
  11.    
  12.    public static void main (String[] args) {
  13.      
  14.       // set up scanner to read input from keyboard
  15.       Scanner scan = new Scanner (System.in);
  16.       // prompt user
  17.       System.out.print("Enter a number: ");
  18.       // read number from keyboard
  19.       long num =  scan.nextLong();
  20.      
  21.       System.out.println("The recursive sum of the digits is "
  22.        +getRecursiveSumOfDigits( num));
  23.      
  24.    }// end main
  25.    
  26.    public static long getRecursiveSumOfDigits(long n) {
  27.       long sum = 0;
  28.       String strNum = ""+n;
  29.  
  30.       // iterate through digits of strNum
  31.       for (int i=0; i<strNum.length(); i++) {
  32.          // add the value of digit i of strNum, to sum
  33.          sum += Integer.valueOf( strNum.substring( i, i+1));
  34.       }
  35.      
  36.       // recursive function call
  37.       if (sum>9) return getRecursiveSumOfDigits(sum);
  38.      
  39.       return sum;
  40.      
  41.    }// end getRecursiveSumOfDigits
  42. }// end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement