Skip to content

Instantly share code, notes, and snippets.

@mumunuu
Last active January 22, 2021 02:19
Show Gist options
  • Save mumunuu/b509dd52d7826ee6792b1b52e0df6fb8 to your computer and use it in GitHub Desktop.
Save mumunuu/b509dd52d7826ee6792b1b52e0df6fb8 to your computer and use it in GitHub Desktop.
algorithm(leetcode) Reverse Integer
func reverse(x int) int {
sign := x >= 0 // sign
abVal := math.Abs(float64(x)) //절대값
t := strconv.Itoa(int(abVal)) // toString
return reverseString(t, sign) // reverse string and get int value
}
func reverseString(s string, sign bool) int {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
reversedString := string(runes) //get reverse string by rune type
i, _ := strconv.Atoi(reversedString) //to int
if i > math.MaxInt32 { //32bit overflow check
return 0
}
if !sign { //sign check
return -i
} else {
return i
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment