Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdulrahmanAlotaibi/1336d1ce9b986b59808559868a91ef92 to your computer and use it in GitHub Desktop.
Save abdulrahmanAlotaibi/1336d1ce9b986b59808559868a91ef92 to your computer and use it in GitHub Desktop.
Reverse Integer
func reverse(x int) int {
if x < int(math.Pow(-2, 31)) || x > int(math.Pow(2, 31)) {
return 0
}
xStr := strconv.Itoa(x)
reversedNumber := ""
// Remove the negative sign
if x < 0 {
xStr = xStr[1:]
}
for i := len(xStr) - 1 ; i >= 0 ; i-- {
reversedNumber += string(xStr[i])
}
num, err := strconv.ParseInt(reversedNumber, 10, 32)
if err != nil {
return 0
}
if x < 0 {
num = num * -1
}
return int(num)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment