Solution in golang


  • 0
    B

    solution in golang
    check overflow before convert.

    func reverse(x int) int {
        output := 0
        arr := strconv.Itoa(x)
        digit := len(arr)
    
        var flag bool
        var limit string
        
        if x >= 0{
            limit = strconv.Itoa(math.MaxInt32)
        } else {
            limit = strconv.Itoa(math.MinInt32)
            limit = limit[1:]
            arr = arr[1:]
            digit --
        }
        
        if digit >= 10 {
            flag = true
        } else {
            flag = false
        }
        
        limitLength := len(limit)
        
        for ;digit >= 1; digit--{
            if flag {
                if arr[digit-1] > limit[limitLength - digit]{
                    return 0
                } else if arr[digit-1] < limit[limitLength - digit] {
                    flag = false;
                }           
            }
            tmp, _ := strconv.Atoi(string(arr[digit-1]))
            output += (tmp * int(math.Pow10(digit-1)))
        }
        
        if x >= 0 {
            return output    
        } else {
            return -1 * output
        }
    }
    

Log in to reply
 

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