Created
December 15, 2022 23:30
-
-
Save abdulrahmanAlotaibi/1336d1ce9b986b59808559868a91ef92 to your computer and use it in GitHub Desktop.
Reverse Integer
This file contains 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 { | |
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