Skip to content

7. Reverse Integer

https://leetcode.com/problems/reverse-integer/

js
/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
  if (x < 0) {
    return -reverse(-x)
  }

  var val = 0
  while (x > 0) {
    val = val * 10 + x % 10
    x = x / 10 >> 0
  }
  return val <= 2147483647 ? val : 0
}
py
class Solution(object):

    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x < 0:
            return -self.reverse(-x)
        val = 0
        while x > 0:
            val = val * 10 + x % 10
            x = x // 10
        return val if val <= 2147483647 else 0
go
func reverse(x int) int {
	if x < 0 {
		return -reverse(-x)
	}

	val := 0
	for x > 0 {
		val = val*10 + x%10
		x = x / 10
	}

	if val <= 2147483647 {
		return val
	}

	return 0
}