leetcode random brushing series - integer reversal
Article directory
1. Topic description
leetcode 7. Integer Reverse
Given a 32-bit signed integer x, return the result of inverting the number part of x.
Returns 0 if the inverted integer exceeds the range [−2^31, 2^31 − 1] of a 32-bit signed integer.
Assume the environment does not allow storing 64-bit integers (signed or unsigned).
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
hint:
-2^31 <= x <= 2^31 - 1
2. Topic analysis
Problem-solving ideas:
The first reaction when seeing the question is to turn the number into a string and then flip the string to get r, and confirm the returned value according to the positive or negative of the input parameter x. If it is >0, it will be directly converted to number to get n, and if it is <0, use parseInt to remove the flipped one. The '-' sign at the end of the string, then take the negative number to get n
let n = x > 0 ? Number(r) : parseInt(r) * -1
The hard condition in the title "If the inverted integer exceeds the range of 32-bit signed integers [−2^31, 2^31 − 1], return 0":
if(n > 2147483647 || n < -2147483648) return 0
else return n
In a special case, the input parameter x is reversed. When x is a single digit, that is, when the absolute value of x |x| < 10, the returned value is still x:
if (-10 < x && x < 10) return x
3. Problem-solving code
code show as below:
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
if (-10 < x && x < 10) return x
// 转字符串
let a = x.toString()
let l = a.length
let r = ''
// 遍历反转得到r字符串
for(let i = 0; i < l; i++){
r += a[l - 1 - i]
}
let n = x > 0 ? Number(r) : parseInt(r) * -1
if(n > 2147483647 || n < -2147483648) return 0
else return n
};