mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-12-19 07:00:35 +08:00
@@ -1,7 +1,9 @@
|
||||
/** Author : Suraj Kumar Modi
|
||||
/**
|
||||
* Author : Suraj Kumar Modi
|
||||
* https://github.com/skmodi649
|
||||
*/
|
||||
/** You are given a number n. You need to find the digital root of n.
|
||||
/**
|
||||
* You are given a number n. You need to find the digital root of n.
|
||||
* DigitalRoot of a number is the recursive sum of its digits until we get a single digit number.
|
||||
*
|
||||
* Test Case 1:
|
||||
@@ -19,7 +21,8 @@
|
||||
* sum of digit of 45 is 9 which is a single
|
||||
* digit number.
|
||||
*/
|
||||
/** Algorithm :
|
||||
/**
|
||||
* Algorithm :
|
||||
* Step 1 : Define a method digitalRoot(int n)
|
||||
* Step 2 : Define another method single(int n)
|
||||
* Step 3 : digitalRoot(int n) method takes output of single(int n) as input
|
||||
@@ -32,14 +35,16 @@
|
||||
* return n;
|
||||
* else
|
||||
* return (n%10) + (n/10)
|
||||
* Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and print the result
|
||||
* Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and
|
||||
* print the result
|
||||
*/
|
||||
package com.thealgorithms.maths;
|
||||
|
||||
class DigitalRoot {
|
||||
|
||||
public static int digitalRoot(int n) {
|
||||
if (single(n) <= 9) { // If n is already single digit than simply call single method and return the value
|
||||
if (single(n) <= 9) { // If n is already single digit than simply call single method and
|
||||
// return the value
|
||||
return single(n);
|
||||
} else {
|
||||
return digitalRoot(single(n));
|
||||
@@ -55,7 +60,6 @@ class DigitalRoot {
|
||||
}
|
||||
} // n / 10 is the number obtainded after removing the digit one by one
|
||||
// Sum of digits is stored in the Stack memory and then finally returned
|
||||
|
||||
}
|
||||
/**
|
||||
* Time Complexity : O((Number of Digits)^2) Auxiliary Space Complexity :
|
||||
|
||||
Reference in New Issue
Block a user