1. 程式人生 > >LeetCode-7. 整數反轉

LeetCode-7. 整數反轉

題目地址:https://leetcode-cn.com/problems/reverse-integer/
題意:字面意思
思路:除了判斷一下溢位,其他沒坑。
AC程式碼:

class Solution {
public:
    int reverse(int x) {
        char min_x[15] = "2147483648";
        char max_x[15] = "2147483647";
        char ans_x[15];
        int flag = x>0?1:-1;
        memset(ans_x,0,sizeof(ans_x));
        ans_x[0] = '0';
        int now = 0;
        int ans = 0;
        while(x){
            int temp = abs(x%10);
            ans_x[now++] = temp+'0';
            x = x/10;
            ans = ans*10+temp;
        }
        if(now<10){
            return ans*flag;
        }
        if(now==10){
            if(flag==1){
                for(int i=0;i<10;i++){
                    if(ans_x[i]>max_x[i]){
                        return 0;
                    }else if(ans_x[i]<max_x[i]){
                        break;
                    }
                    
                }
            }else{
                for(int i=0;i<10;i++){
                    if(ans_x[i]>min_x[i]){
                        return 0;
                    }else if(ans_x[i]<min_x[i]){
                        break;
                    }
                }
            }
            return ans*flag;
        }
    }
};