LeetCode: Reverse Integer (JavaScript)

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

本地测试通过,代码如下:

var reverse = function(x) {
    var res = 0;
    while(x){
        res = res*10 +x%10;
        x = parseInt(x/10);  //(由于js是弱类型语言, 要将x转换为整型)
    }
    return res;
};
当测试用例中有溢出的整数时,会报错,在上述代码中加了两行判断是否溢出

var reverse = function(x) {
    var res = 0;
    while(x){
        res = res*10 +x%10;
        x = parseInt(x/10);
    }
    if(res> Math.pow(2,31) || -res>Math.pow(2,31)){
       res = 0;
    }
    return res;
};




你可能感兴趣的:(LeetCode)