I have written code which takes in a number and multiplies its digits together:
public static int findSum(int k) {
int sum = 0;
while (k != 0) {
sum = sum + ((k % 10) * (k % 10));
k = k / 10;
}
return sum;
}
public static void main(String[] args) {
System.out.println(findSum(713));
}
My code returns 19 when my input is 82, because 12 + 92 is 82.
However, I want to modify my code so that my code would continue to square each digit and add them together until there is only one non-zero digit left.
So basically, if my input is 19, the code would return 1 because:
What changes to my code should I make in order for it to work?
You could call your method recursivly by checking if sum > 9
public static int findSum(int k)
{
int sum = 0;
while (k != 0)
{
sum = sum + ((k % 10)*(k % 10));
k = k/10;
}
return sum > 9 ? findSum(sum) : sum;
}