Reverse Integer in JavaScript


  • 0
    R

    The main ideas are as follows

    Will the number go to the string, according to the first string, set the return value rer to "" or "-". "-" but also on the string substing operation.

    Set a variable "skip" for the case where the first character is "0" after filtering inversion

    Will continue to meet the requirements of the characters and ret added

    Finally, deal with the value is too large or too small

    var reverse = function(x) {
       var el = String(x)
       var a = ''
       if(el[0] == '-' ){
           a = '-'
           el = el.slice(1)
       }
       var skip = true
       for(var i =el.length; i--;){
           var c = el[i]
           if(skip){
               if(c === '0'){
                   skip =true
               }else{
                   skip = false
               }
           }
           if(!skip){
               a += c
           }
           
       }
       
       a =  Number(a)
       //The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
       //32位有符号整数的范围大概是-2^31 ~ 2^31-1
       if(a < -1 * 2**31){
           return 0
       }
       if(a > 2**31-1){
           return 0
       }
       return a
    };
    

    A 32-bit signed integer should be between -2 ^ 31 and 2 ^ 31-1


Log in to reply
 

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