LeetCode 7. Reverse Integer by JavaScript 取整和溢出解决办法(附完整代码)

一、数字反转

1.为何要使用parseInt?

因为在javascript中,3/10=0.3;不等同于java中的取整结果3/10=0;
而parseInt可以保留整数部分,即取整。

2.核心代码

function reverse(){
var ans=0;
while(x){
    var temp=ans*10+x%10;
    if(parseInt(temp/10)!=ans){
        return 0;
    }
    ans=temp;
    x=parseInt(x/10);
}
return ans;
}

二、内存溢出

LeetCode 7. Reverse Integer by JavaScript 取整和溢出解决办法(附完整代码)_第1张图片

1.题目要求

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.

2.32-bit范围

维基百科中32-bit的解释
−2,147,483,648 (−231) through 2,147,483,647 (231 − 1)

3.修改后代码

function reverse(){
    if(x<-2147483648||x>2147483647){
        return 0;
    }
    var ans=0;
    while(x){
        var temp=ans*10+x%10;
        if(parseInt(temp/10)!=ans){
            return 0;
        }
        ans=temp;
        x=parseInt(x/10);
    }
    if(ans<-2147483648||ans>2147483647){
        return 0;
    }
    return ans;
}

4.结果超出了Int的范围

也需要判断溢出,且返回值为0。
LeetCode 7. Reverse Integer by JavaScript 取整和溢出解决办法(附完整代码)_第2张图片

三、完整代码

1.javascript

/**
 * Created by nodrin on 2018/3/15.
 */
window.onload=function(){
    reverse();
}
function reverse(){
    if(x<-2147483648||x>2147483647){
        return 0;
    }
    var ans=0;
    while(x){
        var temp=ans*10+x%10;
        if(parseInt(temp/10)!=ans){
            return 0;
        }
        ans=temp;
        x=parseInt(x/10);
    }
    if(ans<-2147483648||ans>2147483647){
        return 0;
    }
    return ans;
}

2.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script rel="script" src="test.js">script>
head>
<body>
    Hello WebStorm!
body>
html>

你可能感兴趣的:(javascript,LeetCode)