I use javascript to tackle this problem , but when the test number is 1534236469,the expected answer is 0,why?


  • 1
    M

    the test number is 1534236469,the expected answer is 0, but my answer is 9646324351,why?
    here is my code

    /**
     * @param {number} x
     * @returns {number}
     */
    var reverse = function(x) {
        var max = Number.MAX_VALUE+"";
        var min = Number.MIN_VALUE+"";
        var maxl=max.length;
        var minl=min.length;
     var data=x+"";
        var sym="";
        if(data.indexOf('-')>=0){
        	data = data.slice(1);
          sym="-";
        }
        data =data.split("");
        if(data.length==1)return parseInt(data);
        if(data.length%2!=0)//ji
        {
            var mid = (data.length-1)/2;
            for(var i=0;i<mid;i++){
                var t =data[i];
                data[i]= data[data.length-1-i];
                data[data.length-1-i]=t;
            }
        }else if((data.length%2==0)){
            var midnext=data.length/2;
            for(var i=0;i<midnext;i++){
                var t =data[i];
                data[i]= data[data.length-1-i];
                data[data.length-1-i]=t;
            }
        }
        //data[0]="aa";
         var nu=test(0,data);
        	data = data.slice(nu);
       
        if(sym==""&&data.length>=maxl){
            if(data.length==maxl){
            if(compare(0,data)){
                
            }else{
                data=0;
            }}else{
                data=0;
            }
        }else if(sym=="-"&&data.length>=minl){
            if(data.length==minl){
            if(compare(0,data)){
                
            }else{
                data=0;
            }
            }else{
                data=0;
            }
        }
        
     if(data!=0){
        data= data.join("");
        data=sym+data;
      }
        return parseInt(data);
        
    function test(i,data){
    	if(data[i]==0){
    		test(i+1,data);
    	}else{
    		return i;
    	}
    }
    
    function compare(i,data){
        if(data[i]<max[i]){
            return true;
        }else if(data[i]==max[i]){
            if(i==data.length-1)return true;
            compare(i+1,data);
        }else{
            return false;
        }
    } 
    };

  • 0
    L

    What's the range of integer? Maybe it's overflow.


  • 0
    Y

    Check the spoilers in the problem.

    Assume the input is a 32-bit integer

    Assume that your function returns 0 when the reversed integer overflows


  • 0

    At first i thought this could be one advantage for javascript submitter, but it turned out you need to set result to 0 once it is large than 2147483647;


  • 2
    D

    We need to simulate signed-int32 overflow:

    Min = -Math.pow(2,31) OR (1 << 31)

    Max = Math.pow(2,31) - 1

    Return 0 if result overflows.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.