Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Difference of Digits at Alternate Indices in JavaScript



We are required to write a JavaScript function that takes in a number and returns the difference of the sums of the digits at even place and the digits odd place.

Example

The code for this will be −

const num = 123456;
const alternateDifference = (num, res = 0, ind = 0) => {
   if(num){
      if(ind % 2 === 0){
         res += num % 10;
      }else{
         res -= num % 10;
      };
      return alternateDifference(Math.floor(num / 10), res, ++ind);
   };
   return Math.abs(res);
};
console.log(alternateDifference(num));

Output

The output in the console −

3
Updated on: 2020-10-14T07:45:31+05:30

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements