反转整数的每一位(reverse integer)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/woniu317/article/details/47869189

1 题目

Reverse digits of an integer.

Example1: x = 123, return321

Example2: x = -123, return-321

2 分析

需要注意溢出的情况,例如1534236469在int范围内,但是反向之后是不在int范围内的,需要特殊处理,这里要求输出0。

3 实现

int Solution::reverse(int x)
{
	int res = 0;
	bool flag = false;

	int temp;
	while (x)
	{
		temp = res;
		res *= 10;
		if (temp != res/10)
		{
			return 0;
		}
		res += x % 10;
		x = x / 10;
	}
	return res;
}


猜你喜欢

转载自blog.csdn.net/woniu317/article/details/47869189