Here's my solution for finding the digital root of a number. Just for purposes of completion, a digital root is:
"If you take the digits of any number and add them together, and then add the digits of the resulting number together, and continue doing that until you get a single digit, that single digit is the digital root of the original number."
What I was hoping for, is if you guys could take a look and provide a cleaner solution. I'm trying to better myself for an upcoming competition.
import java.util.Scanner;
import java.util.StringTokenizer;
public class DigialRoot {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
System.out.println();
String str = sc.nextLine();
String[] numbers = str.split("");
int[] myList = new int[numbers.length];
for(int i=0; i < numbers.length; i++){
myList[i] = Integer.parseInt(numbers[i]);
}
//add all numbers together
int sum = 0;
for(Integer x : myList){
sum += x;
}
//break down and add sum
String sumStr = Integer.toString(sum);
String[] nums = sumStr.split("");
int[] nxtList = new int[nums.length];
for(int i=0; i < nums.length; i++){
nxtList[i] = Integer.parseInt(nums[i]);
}
//calculating final result of digital root
int result = 0;
for(Integer x : nxtList){
result += x;
}
System.out.println("Original number: " + str);
System.out.println("Digital root: " + result);
}
}