简体   繁体   English

如何在javaScript中对给定的数字和它的反向数字求和

[英]How to sum a given number and it's reverse number in javaScript

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无法弄清楚如何编写代码以求和654 + 456

Thank You very much!非常感谢!

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

You can return sum of num and reversedNum inside a function.您可以在函数内返回 num 和 reversedNum 的总和。

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

let userNumber = 456

console.log(sumOfNumAndReversedNum(userNumber))

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 (eg, 123 % 10 === 3 ) and adding it to your newly reversed number.一种选择是通过弹出最后一个整数(例如, 123 % 10 === 3 )并将其添加到新反转的数字中来向后遍历数字。 You'll also need to multiply your reversed number by 10 in each iteration to move you to the next degree.您还需要在每次迭代中将反转的数字乘以10 ,以将您移动到下一个学位。

For example, given the number 123 :例如,给定数字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))
const reversedNum = num => 
  Number(num.toString().split('').reverse().join(''))

console.log(reversedNum(456))

Do it!去做吧!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM