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: 18-Sep-2020

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements