Leetcode - Reverse Integer

2017-04-21  本文已影响0人  哈比猪

题目链接

Reverse Integer

Reverse digits of an integer.
Example1: x = 123, return 321Example2: x = -123, return -321
click to show spoilers.
**Note:
**The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

解题思路

TODO(稍后补充)

解题代码

class Solution {
public:
    int reverse(signed int x) {
        vector<int> tmp(32,-1);
        long input=0 ,flag = 0, index=0;
        if (x > 0) {
            input = x;
            
        }else {
            input = 0-x;
            flag = 1;
            if (x == min) input = max+1;
            //cout<<"gergerg: "<<input<<endl;
        }
        
        while (input/10 != 0) {
            int residual = input%10;
            input = input/10;
            tmp[index++] = residual;
        }
        tmp[index] = input;
        
        // if reversed integer overflows, return 0
        long output = 0;
        index = 0;
        while (tmp[index] != -1) {
            output = output*10 + tmp[index++];
        }
        
        //cout <<output<<endl;
        if ((flag == 1 && (0 - output) < min) or (flag == 0 && output > max)) {
            return 0;
        }
        
        return flag == 1 ? 0 - output : output;
        
    }
private:
    long max = 2147483647;
    long min = -2147483648;
};
上一篇下一篇

猜你喜欢

热点阅读