Home > Enterprise >  How to sum a given number and it's reverse number in javaScript
How to sum a given number and it's reverse number in javaScript

Time:06-16

const reversedNum = num => 
  parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num)

console.log(reversedNum(456))

Couldn't figure it out how to write code in order to sum 654 456

Thank You very much!

CodePudding user response:

You can return sum of num and reversedNum inside a function.

const sumOfNumAndReversedNum= num => {
  const reversedNum = parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num)
  return num   reversedNum
}

let userNumber = 456

console.log(sumOfNumAndReversedNum(userNumber))

CodePudding user response:

const reversedNum = num => num    num.toString().split('').reverse().join('')

CodePudding user response:

You can write a more performant way of reversing the number than turning it into a string, flipping it, and turning it back into an integer.

One option is to go through the number backwards by popping off the last integer (e.g., 123 % 10 === 3) and adding it to your newly reversed number. You'll also need to multiply your reversed number by 10 in each iteration to move you to the next degree.

For example, given the number 123:

123 % 10 = 3;
123 /= 10 = 12;
0 * 10   3 = 3;

1 % 10 = 2;
12 /= 10 = 1;
3 * 10   2 = 32

1 % 10 = 1;
1 /= 10 = 0;
32 * 10   1 = 321

This method will also automatically take care of negative numbers for you, leaving you something like:

function reverse(num) {
  let reversed = 0;
  
  while (num !== 0) {
    const popped = num % 10;
    num = parseInt(num / 10);
    if (reversed > Number.MAX_VALUE / 10 || (reversed === Number.MAX_VALUE / 10 && popped > 7)) return 0;
    if (reversed < Number.MIN_VALUE / 10 || (reversed === Number.MIN_VALUE / 10 && popped < -8)) return 0;

    reversed = reversed * 10   popped;
  }
  
  return reversed;
}

Now you can simply call:

console.log(123   reverse(123))

CodePudding user response:

const reversedNum = num => 
  Number(num.toString().split('').reverse().join(''))

console.log(reversedNum(456))

Do it!

  • Related