首页 > 代码库 > reverse-integer

reverse-integer

Reverse digits of an integer.

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

//翻转数字 注意点:1.如果数字的最后后几位是0 eg10,100; 2.数字如果溢出如何处理?

class Solution {
public:
    int reverse(int x) {
        int IntMax = INT_MAX;
        int IntMin = INT_MIN;
        bool flag = false;
        int sum = 0;
        
        if(x<0)
        {
            x = abs(x);
            flag = true;
        }
        
        while(x){
            int tmp = x%10;
            sum = sum*10+tmp;
            if(sum > INT_MAX){
                if(flag = true)
                    sum = INT_MIN;
                else 
                    sum = INT_MAX;
            }             
        
            x = x/10;
        }
        
        if(flag){
            sum *= -1;
        }
          
        return sum;
           
    }
};

 

 

 

reverse-integer