【LeetCode】【Python】【C++】7. Reverse Integer代码实现

题目

Reverse digits of an integer.

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

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.


思路:

循环通过对10取模得到尾部数字,一步步乘10构造新的翻转后的整数即可。然而要注意首先判断原数字的正负,最后还要判断结果是否溢出。


python实现:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x>=0:
            flag=1
        else:
            flag=-1

        x=abs(x)
        new_x=0
        while x>=10:
            new_x=new_x*10+x%10
            x=x//10

        new_x=(new_x*10+x)*flag

        if new_x < 2147483648 or new_x >= -2147483648:
            return new_x
        else:
            return 0


C++实现:

#include
#include 

using namespace std;


class Solution {
public:
	int reverse(int x) {
		int flag;
		if (x > 0) flag = 1;
		else flag = -1;
		x = abs(x);
		long long new_x = 0;
		while (x >= 1)
		{
			new_x =  new_x * 10 + x % 10;
			x = x / 10;
		
		}

		new_x = new_x*flag;
		if (new_x > INT_MAX || new_x < INT_MIN) return 0;
		else return new_x;
	}
};

int main()
{
	int test = 1534236469;
	Solution a;
	int b = a.reverse(test);
	cout << b;
	cin.get();
}

猜你喜欢

转载自blog.csdn.net/qq_16340693/article/details/70665805
今日推荐