Greatest digit of a number in 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

Example

The code for this will be −

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

The output in the console will be −

6

Updated on: 17-Oct-2020

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements