Leetcode 7:Reverse Integer(整数反转)

Description:

Given a 32-bit signed integer, reverse digits of an integer.
给出一个 32 位的有符号整数,将这个整数每位上的数字进行前后反转。

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [ − 2 31 [-2^{31} [231, 2 31 − 1 ] 2^{31}-1] 2311]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [ − 2 31 [-2^{31} [231, 2 31 − 1 ] 2^{31}-1] 2311]。请根据这个假设,如果反转后整数溢出那么就返回 0。

Example

Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
值得注意的点:
  • 题解中给出的函数原型为 int reverse(int x),输入参数为 int 型,返回 int 型
  • 输入 int 型的值,反转后可能会超出 int 范围

Solution 1: 利用求余算出各位数字,再逆向还原成反转整数(函数实现:18-60行)

/* 将数字逐位逆序求出,并进行处理,得出题解 */
#include <iostream>
#include <climits>	// INT_MIN, INT_MAX
#include <vector>

using namespace std;

int reverse(int x);

int main()
{
	int a;
	cin >> a;
	cout << reverse(a) << endl;
	return 0;
}

int reverse(int x)
{
	long long res = 0;	// 	用 long long 类型存放结果,以防溢出
	int x1 = x;
	vector<int> v;	//	存放输入整数各个位上的数字,从末尾到首位
	int tmp = 0;

	if (x1 > 0)	// 输入正数时
	{
		while (x1 > 0)
		{
			tmp = x1 % 10;
			x1 = x1 / 10;
			v.push_back(tmp);
		}
		for (int i = v.size()-1, j = 1; i >= 0; i--)
		{	//	逆向计算出反转整数
			res = res + j * v.at(i);
			j = j * 10;
		}
	}
	else if (x1 < 0)	// 输入负数时
	{
		while (x1 < 0)
		{
			tmp = x1 % 10;
			x1 = x1 / 10;
			v.push_back(tmp);
		}
		for (int i = v.size()-1, j = 1; i >= 0; i--)
		{
			res = res + j * v.at(i);
			j = j * 10;
		}
	}
	else	// 输入0时
		res = 0;

	if (res > INT_MAX || res < INT_MIN)	// 反转后整数溢出则返回 0
		return 0;
	else
		return res;
}
复杂度:

在这里插入图片描述

Solution 2: 将数字转化为字符串,再进行反转、去0(函数实现:17-52行)

#include <iostream>
#include <climits>	// INT_MIN, INT_MAX
#include <algorithm>	// std::reverse()

using namespace std;

int reverse(int x);

int main()
{
	int a;
	cin >> a;
	cout << reverse(a) << endl;
	return 0;
}

int reverse(int x)
{
	long long res;	// 	用 long long 类型存放结果,以防溢出
	if (x > 0)	// 正整数
	{
		string s = to_string(x);	// 整数转化为字符串

		while (s.back() == '0')	//	去除整数(字符串)后面的0
		{
			s = s.erase(s.length()-1);
		}
		
		std::reverse(s.begin(), s.end());	 // 反转字符串
		res = stoll(s);	// 再转化为 long long 型整数
	}
	else if (x < 0)	// 负数
	{
		string s = to_string(x);
		s = s.erase(0, 1);	// 去除负号

		while (s.back() == '0')
		{
			s = s.erase(s.length()-1);
		}

		std::reverse(s.begin(), s.end());
		res = -stoll(s);
	}
	else
		res = 0;
	
	if (res > INT_MAX || res < INT_MIN)
		return 0;
	else
		return res;
}
复杂度:

在这里插入图片描述
目瞪口呆,开心哈哈哈哈hO(∩_∩)O~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值