Skip to content

Instantly share code, notes, and snippets.

@lkrych
Created April 24, 2018 15:46
Show Gist options
  • Save lkrych/c3a3ea0e2a9cc151e8e5827dda88b2fa to your computer and use it in GitHub Desktop.
Save lkrych/c3a3ea0e2a9cc151e8e5827dda88b2fa to your computer and use it in GitHub Desktop.
Solution for reversing an integer
func reverse(x int) int {
neg := 1
ans := 0
if x < 0 {
//make sure to only work with positive numbers
x *= -1
neg = -1
}
//the business loop!
for x > 0 {
ans *= 10
ans += x %10
x = x/10
}
//catch overflow
if ans > 2147483648 || ans < (2147483648 * -1) {
return 0
}
return ans * neg
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment