https://leetcode-cn.com/problems/reverse-integer/description/
给定一个 32 位有符号整数,将整数中的数字进行反转。
示例 1:
输入: 123 输出: 321
示例 2:
输入: -123 输出: -321
示例 3:
输入: 120 输出: 21
注意:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。
以字符串方式思考:
C++:
class Solution {
public:
int reverse(int x) {
string strHXTest = to_string(x);
string strHXTestResult;
int nIndex = 0;
//"-"代表字符串 会多一步转换
if (strHXTest.at(nIndex) == '-')
{
strHXTestResult += strHXTest.at(nIndex);
++nIndex;
}
int nSize = strHXTest.find_last_not_of('0');
while (nIndex <= nSize)
{
strHXTestResult += strHXTest.at(nSize);
--nSize;
}
//尝试使用流操作
istringstream streanResult(strHXTestResult.c_str());
//防止转后超过int的上下限
long nResult = 0;
streanResult >> nResult;
if (nResult > INT32_MAX || nResult < INT32_MIN)
{
nResult = 0;
}
return nResult;
}
};
python:
数字方式思考:
需要判断取值范围,反转后可能为大于int32的数
class Solution {
public:
int reverse(int x) {
long nResult = 0;
while (true)
{
nResult = nResult * 10 + x % 10;
x /= 10;
if (x == 0)
{
break;
}
}
return nResult;
}
};