首页 > 代码库 > 【LeetCode】Reverse Integer

【LeetCode】Reverse Integer

      题意:

     Reverse digits of an integer.

     Example1: x = 123, return 321
     Example2: x = -123, return -321


     思路:

     把整数倒转。很容易,只要先判断是否负数,存起来。之后取绝对值,把绝对值倒转后再决定是否是负数。


     代码:

class Solution {
public:
    int reverse(int x) {
		bool neg = (x < 0);

		x = abs(x);

		int ans = 0;

		while(x)
		{
			int t = x%10;
			ans = ans*10 + t;
			x = x/10;
		}

		if(neg) ans = -ans;

		return ans;
    }
};

     Python:

class Solution:
    # @return an integer
    def reverse(self, x):
        flag = x < 0
        x = abs(x)
        x = list(str(x))
        x.reverse()
        x = ''.join(x)
        if flag:
            return int('-'+x)
        else:
            return int(x)



【LeetCode】Reverse Integer