Reverse Integer
MediumThe problem
Reverse the digits of the integer x and return the result, keeping the sign. If the reversed number does not fit in a signed 32-bit integer (below -2,147,483,648 or above 2,147,483,647), return 0.
- Example 1Input: x = 123Output: 321
- Example 2Input: x = -123Output: -321
- Example 3Input: x = 120Output: 21
The zero ends up at the front and disappears.
- Example 4Input: x = 1534236469Output: 0
The reverse, 9646324351, is larger than 2,147,483,647.
- -2,147,483,648 ≤ x ≤ 2,147,483,647
Write it in Go. Try for about 20 minutes on paper first, then open one hint at a time.
Try it here
Write Go. Common packages like fmt and sort are imported for you. Keep the function name and inputs the same.
Hints, one at a time
Nudge
Peel digits off with % 10 and push them on with ×10. Watch for overflow before it happens.
The idea
Loop digit = x % 10; x /= 10; check that rev·10 + digit stays within the 32-bit range before updating.
Target: O(log x) time
Go function shape
func reverse(x int) intReference solution
Tested with go test. Try it yourself first, then compare.
// Reverse: reverse the digits of a 32-bit integer, or 0 if the result would overflow.
// The overflow check happens BEFORE multiplying, because afterwards it is too late.
func Reverse(x int) int {
rev := 0
for x != 0 {
digit := x % 10
x /= 10
if rev > math.MaxInt32/10 || (rev == math.MaxInt32/10 && digit > 7) {
return 0
}
if rev < math.MinInt32/10 || (rev == math.MinInt32/10 && digit < -8) {
return 0
}
rev = rev*10 + digit
}
return rev
}