Description
Given a 32-bit signed integer, reverse digits of an integer.
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.
AC代碼
class Solution {
public:
int reverse(int x) {
long long ret=0;
while(x != 0) {
ret = ret * 10 + x % 10;
x /= 10;
if((ret > INT32_MAX) || (ret < INT32_MIN)) {
return 0;
}
}
return ret;
}
};
測(cè)試代碼
int main() {
Solution s;
cout << s.reverse(1534236469) << " " << s.reverse(-123) << endl;
}
總結(jié)
反轉(zhuǎn)整數(shù)是一道比較經(jīng)典的算法題目邪乍,處理思路就是通過(guò)%10一步步把整數(shù)的最后一位剝離出來(lái),剩下的數(shù)就是/10贞绵。再對(duì)剩下的數(shù)進(jìn)行相同的操作治唤,直到x=0為止剔应。