leetcode--Reverse Integer

1.题目描述

Reverse digits of an integer.
 
Example1: x = 123, return 321
Example2: 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() function
        bool 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;
        
    }
};
posted @ 2013-08-19 22:21  曾见绝美的阳光  阅读(245)  评论(0编辑  收藏  举报