7. Reverse Integer

Description

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321

Constraints:

  • -2^31 <= x <= 2^31 - 1

Tags

Math

Solution

Our goal is to move units digit of x to the end of ans. We can achieve this by performing ans = ans*10 + x%10; x /= 10 until x == 0. After this loop, we need to check if the result is out of the signed 32-bit integer range. If it does go outside of the range, we return 0 rather than ans.

Complexity

  • Time complexity: O(n)O(n)

  • Space complexity: O(1)O(1)

Code

func reverse(x int) int {
	var ans int
	for ; x != 0; x /= 10 {
		ans = ans*10 + x%10
	}
	if ans > 1<<31-1 || ans < -(1<<31) {
		return 0
	}
	return ans
}

Last updated

Was this helpful?