颠倒整数 c++算法 leetcode7

题目:颠倒整数

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1: 

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。根据这个假设,如果反转后的整出,则返回 0。

解答:

①翻转数字问题需要注意的就是溢出问题。

       为什么会存在溢出问题呢,我们知道int型的数值范围是 -2147483648~2147483647, 那么如果我们要翻转 1000000009 这个在范围内的数得到 9000000001,而翻转后的数就超过范围。用long long 型数据,数值范围-9223372036854775808~9223372036854775807, 远大于int型这样就不会出现溢出问题。

②解题思路

      先判断是否为负数,为负数乘以-1,当为正数时直接进入循环,然后判断是否超限返回0值。再判断标志变量,添加回正负号。

代码示例:

      1.类的封装

class Solution 
{
public:
	int reverse(int x)
	{
		long long res = 0;
		bool isPosition = true;
		if (x < 0)
		{
			isPosition = false;
			x *= -1;
		}
		while (x > 0)
		{
			res = res * 10 + x % 10;
			x /= 10;
		}
		if (res > INT_MAX)
			return 0;
		if (isPosition)
			return res;
		else
			return -res;
	}
};

2.头文件

#include<iostream>
#include<vector>

using namespace std;

3.z主函数

int main()
{
	int a = 0.7;
	cout << a << endl;
	int b = 321;
	class Solution pt;
	int c = pt.reverse(b);

	cout << c << endl;
}

写的代码都在VS2015下测试没有问题,如果输入为int b = 321;

输出为

补充

int a = 0.7;
 cout << a << endl;

当数值类型为int,取值小于1时。其值直接为0,保证class Solution里面while()跳出循环。

该题所有测试代码如下

#include<iostream>
#include<vector>
using namespace std;

class Solution 
{
public:
	int reverse(int x)
	{
		long long res = 0;
		bool isPosition = true;
		if (x < 0)
		{
			isPosition = false;
			x *= -1;
		}
		while (x > 0)
		{
			res = res * 10 + x % 10;
			x /= 10;
		}
		if (res > INT_MAX)
			return 0;
		if (isPosition)
			return res;
		else
			return -res;
	}
};

int main()
{
	int a = 0.7;
	cout << a << endl;
	int b = 321;
	class Solution pt;
	int c = pt.reverse(b);

	cout << c << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_37648020/article/details/83620832