Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
本体给出一个整数要求把整数反转,不过需要注意的是,反转整数的结果,正反符号需要保留且结果不在范围之内需返回零。
最先想到的方法:
思路:整数先转字符串,然后使用JS自带的反转函数进行字符串反转。反转后带上符号转成整数返回。提交后只有10%的超越率
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
const isNegative=x<0;
let result=(''+Math.abs(x)).split('').reverse().join('');
result=isNegative?'-'+result:result;
result=parseInt(result);
if(result<-2147483648||result>2147483647){return 0;}
return result;
};
取余:
思路:对一个整数不断的取余。
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
const isNegative=x<0;
x=Math.abs(x);
let result=''
while(x){
const remainder=x%10;
result+=(remainder);
x=Math.floor(x/10);
}
result =isNegative?'-'+result:result;
if(result<-2147483648||result>2147483647){return 0;}
return Math.floor(result);
};