LeetCode[7]Reverse Integer

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/khy19940520/article/details/77995048
Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

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


本地可执行程序:

#include<iostream>
using namespace std;

/*
解题思路:把数字对10取余,在乘10逐渐累加,最后判断溢出
*/

int reverse(int x);

int main()
{
	int result;
	int a = -12345006;
	result = reverse(a);
	cout << result << endl;
	system("pause");
	return 0;
}

int reverse(int x)
{
	long long sum = 0;
	//反转
	while (x != 0)
	{
		int s = x % 10;
		sum = sum * 10 + s;
		x = x / 10;
	}
	//判断溢出
	if (sum > INT_MAX || sum < INT_MIN)
	{
		return 0;
	}
	else
	{
		return sum;
	}
}


提交代码:

class Solution {
public:
    int reverse(int x) 
    {
        long long sum=0;
        while(x!=0)
        {
            int s = x%10;
            sum = sum*10 + s;
            x = x/10;
        }
        if(sum > INT_MAX || sum < INT_MIN)
        {
            return 0;
        }
        else
        {
            return sum;
        }
        
    }
};



猜你喜欢

转载自blog.csdn.net/khy19940520/article/details/77995048