Given a 32-bit signed integer, reverse digits of an integer.
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
32비트 부호를 가진 integer가 주어질 때, 역순의 값을 구하라.
// 인터넷에 찾아보니, 양수 integer를 역순으로 처리하는 방법은 있었기 때문에
// 음수일 때의 처리만 추가해주었다.
func reverse(x int) int {
new_int := 0
if x >= 0 {
for x > 0 {
remainder := x % 10
new_int *= 10
new_int += remainder
x /= 10
}
return new_int
} else {
x *= -1
for x > 0 {
remainder := x % 10
new_int *= 10
new_int += remainder
x /= 10
}
return new_int * (-1)
}
}
이렇게 했다가 대차게 틀렸다.
예시는 맞았는데, 제출하니 오답처리가 되었다.
이유를 생각해보니, note
를 읽지않은 것이 문제.
수정했다.
func reverse(x int) int {
new_int := 0
if x >= 0 {
for x > 0 {
remainder := x % 10
new_int *= 10
new_int += remainder
x /= 10
}
// int32 최대값을 초과하는지를 확인하는 조건을 추가했다.
if new_int > math.MaxInt32 {
return 0
}
return new_int
} else {
x *= -1
for x > 0 {
remainder := x % 10
new_int *= 10
new_int += remainder
x /= 10
}
// int32 최소값을 초과하는지를 확인하는 조건을 추가했다.
if new_int * (-1) < math.MinInt32 {
return 0
}
return new_int * (-1)
}
}
func reverse(x int) int {
//math.MinInt32 = -2147483648
//math.MaxInt32 = 2147483647
var result int
for x!=0{
result=result*10+x%10
if result > 2147483647 || result < -2147483648{
return 0
}
x/=10
}
return result
}
func reverse(x int) int {
var result int
for x != 0 {
result = result * 10 + x % 10
x = x / 10
}
if result < math.MinInt32 || result > math.MaxInt32 {
return 0
}
return result
}