Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding greatest digit by recursion - JavaScript
We are required to write a JavaScript recursive function that takes in a number and returns the greatest digit in the number.
For example: If the number is ?
45654356
Then the return value should be 6
How It Works
The recursive approach extracts digits one by one from right to left using modulo (%) and integer division. Each digit is compared with the current maximum, and the function calls itself with the remaining digits.
Example
Following is the code ?
const num = 45654356;
const greatestDigit = (num = 0, greatest = 0) => {
if(num){
const max = Math.max(num % 10, greatest);
return greatestDigit(Math.floor(num / 10), max);
};
return greatest;
};
console.log(greatestDigit(num));
Output
Following is the output in the console ?
6
Step-by-Step Breakdown
Let's trace through the execution with number 45654356:
const traceGreatestDigit = (num = 0, greatest = 0, step = 1) => {
console.log(`Step ${step}: num=${num}, greatest=${greatest}`);
if(num){
const currentDigit = num % 10;
const max = Math.max(currentDigit, greatest);
console.log(` Current digit: ${currentDigit}, New max: ${max}`);
return traceGreatestDigit(Math.floor(num / 10), max, step + 1);
};
console.log(`Final result: ${greatest}`);
return greatest;
};
traceGreatestDigit(45654356);
Step 1: num=45654356, greatest=0 Current digit: 6, New max: 6 Step 2: num=4565435, greatest=6 Current digit: 5, New max: 6 Step 3: num=456543, greatest=6 Current digit: 3, New max: 6 Step 4: num=45654, greatest=6 Current digit: 4, New max: 6 Step 5: num=4565, greatest=6 Current digit: 5, New max: 6 Step 6: num=456, greatest=6 Current digit: 6, New max: 6 Step 7: num=45, greatest=6 Current digit: 5, New max: 6 Step 8: num=4, greatest=6 Current digit: 4, New max: 6 Step 9: num=0, greatest=6 Final result: 6
Alternative Approach
Here's another recursive implementation that handles negative numbers:
const findGreatestDigit = (num) => {
// Convert to positive and handle base case
num = Math.abs(num);
if (num
6
9
7
Conclusion
Recursive digit extraction uses modulo and integer division to process each digit. The function maintains the maximum value found so far and returns it when no digits remain.
