Given a 32-bit signed integer, reverse digits of an integer.
给出一个32位有符号的整数,请你颠倒整数的数字。
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
假设32位有符号的整数的范围是[-231,231-1]。若反转后的整数溢出,假定此时你的函数返回零。
分析:
通过reverse反转字符串,用s='-'+s
处理负号的问题,stoi
消除前置零,
if( stoll(s) > INT_MAX || stoll(s) <INT_MIN )
处理数据溢出的特殊情况。
C++代码①
class Solution {
public:
int reverse(int x) {
string s = to_string(x);
std::reverse(s.begin(),s.end());
if(s.back()=='-') s='-'+s;
if( stoll(s) > INT_MAX || stoll(s) <INT_MIN ) return 0;
return stoll(s);
}
};