LeetCode :7. Reverse Integer


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

 Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


python:

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        positive = True
        if x < 0:
            positive = False
        x = abs(x)
        ans = 0
        while x > 0:
            ans = ans * 10 + x % 10
            x //= 10
        if ans > 2147483647:
            return 0
        if not positive:
            return -1*ans
        return ans


JavaScript:

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    var res = 0; 
	while(x){ 
		res = res*10 +x%10; 
		x = parseInt(x/10); 
	} 
	if(res> Math.pow(2,31) || -res>Math.pow(2,31)){ //2的31次方,防溢出
		res = 0; 
	} 
	return res;
};

猜你喜欢

转载自blog.csdn.net/h330531987/article/details/80049825