leetcode - 7. Reverse Integer
Degree
Easy ★ (*´╰╯`๓)♬
Description:
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Example1:
Input: 123
Output: 321
Example2:
Input: -123
Output: -321
Example3:
Input: 120
Output: 21
Ideas
- 模十法,将各位的数字依次往最高位升
- 初始为负数的依然为负数形式
- 当数字大小茶超过2^32的时候,就返回0
Code
var reverse = function(x) {
var y = Math.abs(x);
var result = 0;
while(y > 0){
result = result * 10 + y % 10;
y = parseInt(y / 10);
}
result = x < 0 ? -result : result;
return result >= -Math.pow(2,31) && result <= Math.pow(2,31) - 1 ? result : 0;
};