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;
}

二、內存溢出

初始值超出int範圍

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。
結果超出int範圍

三、完整代碼

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script rel="script" src="test.js"></script>
</head>
<body>
    Hello WebStorm!
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章