[Go] LeetCode 7. Reverse Integer

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
}

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
TAKASHI NARIKAWA

TAKASHI NARIKAWA

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

More from Medium

How To Begin With Golang | Part 3

How To Periodically Check MongoDB Replica Set Status

Bubble Sort in Go

Leetcode with Golang: Longest Common Prefix