首页 > 代码库 > Reverse Integer

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;
        }
    }
};


Reverse Integer