美文网首页
Leetcode - Reverse Integer

Leetcode - Reverse Integer

作者: 哈比猪 | 来源:发表于2017-04-21 19:58 被阅读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;
    };
    

    相关文章

      网友评论

          本文标题:Leetcode - Reverse Integer

          本文链接:https://www.haomeiwen.com/subject/lchjzttx.html