7. The front end of an integer inversion algorithm leetcode

7. The front end of the # integer inversion algorithm leetcode

Title Description

Gives a 32-bit signed integer, you need this integer number on each inverted.

Example 1:

输入: 123
输出: 321

 Example 2:

输入: -123
输出: -321

Example 3:

输入: 120
输出: 21
注意:

Suppose we have an environment can only store a 32-bit signed integer, then the value range [-2 ^ 31, 2 ^ 31 - 1] Please According to this hypothesis, if integer overflow after reverse it returns 0.

7. integer reversal

Overview

prompt

It should be noted that the overflow2**31到-(2**31)

Resolve

Recursive cycle, note overflow condition

solution

If you do not consider the overflow problem, then it is very simple (strange), with js solution of this question has two pits, the first one is the variable lift, when the integers modulo operations such as multiplication and division, will turn into a floating-point number, obtained results There 0!=0circumstances, we need to use these results Math.flooror ~~to round pick before they can operate more than

algorithm

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function (x) {
  let ans = 0;
  while (x !== 0) {
    ans = ans * 10 + ~~(x % 10);
    x = ~~(x / 10);
  }
  return (ans >= (2 ** 31) || ans <= -(2 ** 31)) ? 0 : ans;
};

Incoming operating results of test cases

input:123
output:321

Results of the

执行用时 :80 ms, 在所有 javascript 提交中击败了94.48%的用户
内存消耗 :35.8 MB, 在所有 javascript 提交中击败了36.81%的用户

GitHub repository

7. integer reversal

Guess you like

Origin www.cnblogs.com/moshuying/p/11903463.html