因为在javascript中,3/10=0.3;不等同于java中的取整结果3/10=0;
而parseInt可以保留整数部分,即取整。
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;
}
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.
维基百科中32-bit的解释
−2,147,483,648 (−231) through 2,147,483,647 (231 − 1)
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;
}
/**
* 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;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script rel="script" src="test.js">script>
head>
<body>
Hello WebStorm!
body>
html>