整数反转
推荐一个好用的网站:类似于c++百科
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnx13t/
来源:力扣(LeetCode)
题目描述:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 :
输入: 123 输出: 321 输入: 120 输出: 21
答案v1.0
// 实现思路:先将数存储到字符数组(字符串)中,然后再对其进行反转。
class Solution
{
public:
int reverse(int x)
{
if (x > 0)
{
string str = to_string(x);
std::reverse(str.begin(), str.end());
if (str < "2147483648" || string("2147483648").size() > str.size())
{
int temp = stoi(str);
return temp;
}
}
else if (x < 0)
{
string str = to_string(x);
std::reverse(str.begin() + 1, str.end());
if (str <= "-2147483648" || string("-2147483648").size() > str.size())
{
int temp = stoi(str);
return temp;
}
}
return 0;
}
};