patternjavaMinor
Digital root recursive function
Viewed 0 times
digitalrecursivefunctionroot
Problem
Haven't any experience writing recursive functions.(Generally tend to avoid them - not sure if that's a negative). What do you think about the following?
This is also my first time using JUnit, I'd appreciate input if I'm doing something wrong there.
Challenge: Create a digital Root Function.
Specifications:
A digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n.
If the resulting value has two digits, continue reducing until a single-digit number is produced.
This is only applicable to the natural numbers.
Solution:
Tests:
This is also my first time using JUnit, I'd appreciate input if I'm doing something wrong there.
Challenge: Create a digital Root Function.
Specifications:
A digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n.
If the resulting value has two digits, continue reducing until a single-digit number is produced.
This is only applicable to the natural numbers.
Solution:
public static int getDigitalRoot(int num) {
if (Integer.toString(num).length() == 1) { return num; }
int result = 0;
for (char c : Integer.toString(num).toCharArray()) {
result += Character.getNumericValue(c);
}
return getDigitalRoot(result);
}Tests:
@Test
public void Tests() {
assertEquals(6 , Utilities.getDigitalRoot(942));
assertEquals(7, Utilities.getDigitalRoot(16));
}Solution
With a bit of knowledge of modular math then you can know that for numbers > 0
This simplifies the algorithm a bit.
If you still want the looped version you can do a variation; instead of using another variable to hold the result and retrying until smaller than 10 just do this:
It works for roughly the same reason as the first modulo operation.
getDigitalRoot(n)== n%9 except when dividable by 9 then it is 9.This simplifies the algorithm a bit.
public static int getDigitalRoot(int n) {
if(n==0)
return 0;
if(n%9 == 0)
return 9;
return n%9;
}If you still want the looped version you can do a variation; instead of using another variable to hold the result and retrying until smaller than 10 just do this:
while (num >= 10) {
num = num/10 +num % 10;
}It works for roughly the same reason as the first modulo operation.
Code Snippets
public static int getDigitalRoot(int n) {
if(n==0)
return 0;
if(n%9 == 0)
return 9;
return n%9;
}while (num >= 10) {
num = num/10 +num % 10;
}Context
StackExchange Code Review Q#79361, answer score: 8
Revisions (0)
No revisions yet.