Created
April 24, 2018 15:46
-
-
Save lkrych/c3a3ea0e2a9cc151e8e5827dda88b2fa to your computer and use it in GitHub Desktop.
Solution for reversing an integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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