Greatest digit of a number in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 17-Oct-2020 11:16:54
Advertisements