[Go] LeetCode 7. Reverse Integer

TAKASHI NARIKAWA
1 min readJan 16, 2020

Description

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution

This solution code includes 3 steps.

  1. pop operation
  2. check beforehand whether or not appending push ope would cause overflow.
  3. push operation
/* [Go] Approach 1: Pop and Push Digits & Check before Overflow */
//MaxInt32 == 32767
func reverse(x int) int {
var rev int
for x != 0 {
//1.pop operation
pop := x % 10
x /= 10

//2.check beforehand whether or not appending push ope would cause overflow.
if ( rev > math.MaxInt32/10 || (rev == math.MaxInt32/10 && pop > 7)){
return 0
}
if ( rev < math.MinInt32/10 || (rev == math.MinInt32/10 && pop < -8)){
return 0
}

//3. push operation
rev = rev * 10 + pop
}
return rev
}

--

--

TAKASHI NARIKAWA

Site Reliablity Engineer in Tokyo. SRE/devops/Go/AWS/Terraform/Kubernetes/Docker