1.题目描述
Reverse digits of an integer.Example1: x = 123, return 321Example2: x = -123, return -321
2.解法分析
解法需注意:
- 为零的状况
- 为负数的状况
- 溢出怎么处理
- 结尾一串0怎么处理
代码如下:
class Solution {public:int reverse(int x) {// Start typing your C/C++ solution below// DO NOT write int main() functionbool isNegative=false;if(x<0)isNegative=true;if(x==0)return 0;x=abs(x);int result=0;while(x%10==0){x/=10;}while(x){result=result*10+x%10;x/=10;}if(result<0)return -1;if(isNegative)result*=-1;return result;}};