Last active
January 22, 2021 02:19
-
-
Save mumunuu/b509dd52d7826ee6792b1b52e0df6fb8 to your computer and use it in GitHub Desktop.
algorithm(leetcode) 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 { | |
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