Finding lunar sum of Numbers - JavaScript



Lunar Sum

The concept of lunar sum says that the sum of two numbers is calculated, instead of adding the corresponding digits, but taking the bigger of the corresponding digits.

For example βˆ’

Let’s say,

a = 879 and b = 768

(for the scope of this problem, consider only the number with equal digits)

Then the lunar sum of a and b will be βˆ’

879

We are required to write a JavaScript function that takes in two numbers and returns their lunar sum.

Example

Following is the code βˆ’

const num1 = 6565;
const num2 = 7385;
const lunarSum = (num1, num2) => {
   const numStr1 = String(num1);
   const numStr2 = String(num2);
   let res = 0, temp;
   for(let i = 0; i < numStr1.length; i++){
      temp = Math.max(+numStr1[i], +numStr2[i]);
      res = (res*10) + temp;
   };
   return res;
};
console.log(lunarSum(num1, num2));

Output

Following is the output in the console βˆ’

7585
Updated on: 2020-09-18T09:30:04+05:30

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements