Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return – –321

#include<iostream>
#include<time.h>
using namespace std;
class Solution {
private:
    bool myError;
    
    void setError(const bool b){myError=b;}
public:
    Solution():myError(false){}
    bool GetError() const {return myError;}
    int reverse(int x) {
        setError(false);
        bool isPositive=true;
        if(x < 0){
            isPositive=false;
            x=x*(-1);
        }
        int r=0;
        int y;
        while(x){
            y=x%10;
            r=r*10+y;
            x=x/10;
            if(r<0){
                setError(true);
                return 0;
            }
        }
        if(isPositive== false)
            r=r*(-1);
        return r;

    }
};
int main()
{
    Solution s;
    int t=s.reverse(1000000003);
    if(s.GetError()==false)
        cout<<t<<endl;
    else
        cout<<"overflow"<<endl;

    t=s.reverse(-10003);
    if(s.GetError()==false)
        cout<<t<<endl;
    else
        cout<<"overflow"<<endl;
    system("pause");
    return 0;
}
posted @ 2014-06-11 22:08  sxcww  阅读(211)  评论(0编辑  收藏  举报