Go solution


  • 0
    A

    It's a little disgusting to consider overflow

    func reverse(x int) int {
    	if x-int(int32(x)) > 0 { //overflow
    		return 0
    	}
    	flag := 1
    	ans := x % 10
    	if x < 0 {
    		x = -x
    		ans = x % 10
    		flag = -1
    	}
    
    	x = x / 10
    	for ; x > 0; x = x / 10 {
    		ans = ans*10 + x%10
    		if ans != int(int32(ans)) { //overflow
    			return 0
    		}
    	}
    	ans = ans * flag
    	if ans != int(int32(ans)) { //overflow
    		return 0
    	}
    	return ans
    }
    
    

Log in to reply
 

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