leetcode题解||Reverse Integer 问题

problem:

Reverse digits of an integer.

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

thinking:

(1)整型反转直观非常easy理解。

如正负,尾数为0等问题还优点理。

(2)反转溢出问题要细致处理。

code:

class Solution {
public:
    int reverse(int x) {
        long long int y=x;
        bool flag=true;
        if(x==0)
            return 0;
        if(x<0)
        {
            y=-x;
            flag=false;
        }
         long long int tmp=10;
        int n=1;
        int m=1;
        long long  int result = 0;
        while((y/tmp)!=0)
        {
            tmp*=10;
            n++;
        }
        tmp=tmp/10;
        for(int i=n;i>0;i--)
        {
            long long int a=y/tmp;
            cout<<a<<endl;
            y=y%tmp;
            tmp=tmp/10;
            result+=a*m;
            m*=10;
        }
        if(abs(result)>2147483647)
            return 0;
        else if(!flag)
            return (-result);
        else
            return result;

    }
};

原文地址:https://www.cnblogs.com/zfyouxi/p/5284306.html