Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner; // to read data
- public class RecursiveDigitAdder {
- /**
- * Program: RecursiveDigitAdder.java
- * Purpose: Keep adding sum of digits until sum <= 9
- * Creator: Chris Clarke
- * Created: 17.12.2012
- */
- public static void main (String[] args) {
- // set up scanner to read input from keyboard
- Scanner scan = new Scanner (System.in);
- // prompt user
- System.out.print("Enter a number: ");
- // read number from keyboard
- long num = scan.nextLong();
- System.out.println("The recursive sum of the digits is "
- +getRecursiveSumOfDigits( num));
- }// end main
- public static long getRecursiveSumOfDigits(long n) {
- long sum = 0;
- String strNum = ""+n;
- // iterate through digits of strNum
- for (int i=0; i<strNum.length(); i++) {
- // add the value of digit i of strNum, to sum
- sum += Integer.valueOf( strNum.substring( i, i+1));
- }
- // recursive function call
- if (sum>9) return getRecursiveSumOfDigits(sum);
- return sum;
- }// end getRecursiveSumOfDigits
- }// end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement