Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

简单模拟

class Solution {
public:
    int reverse(int x) {
        char s[1111];
        sprintf(s,"%d",x);
        int len=strlen(s);
        int ans=0;
        if(s[0]=='-'){
            int g=1;
            for(int i=1;i<len;i++){
                ans+=(g*(s[i]-'0'));
                g*=10;
            }
            ans=-ans;
            return ans;
        }
        else{
            int g=1;
            for(int i=0;i<len;i++){
                ans+=(g*(s[i]-'0'));
                g*=10;
            }
            return ans;
        }
    }
};


posted @ 2017-07-06 20:00  yxysuanfa  阅读(130)  评论(0编辑  收藏  举报