Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

注:这真是个破题!但是我的时间复杂度似乎还挺好。
Runtime: 12 ms .Your runtime beats 99.92 % of c submissions.

int reverse(int x) {
    //溢出情况
    if(x > 2147483647 || x < -2147483648)
        return 0;
    //队列
    int que[100];
    int rear = 0, front = 0;
    
    int flag = 0;// 0为负数,1为正数
    //向队列中装数字
    if(x > 0){
        flag = 1;
        while(x > 0){
            que[++rear] = (x%10);
            x = x/10;
        }
    }else if(x < 0){
        while (x < 0){
            que[++rear] = -1*(x%10);
            x = x/10;
        }
    }else{
        return 0;
    }
    
    long long result = 0;
    long long mul = 1;
    front++;
    if(que[front] == 0)
        front++;
    while(rear != front){
        for(int i = 0; i < rear-front; ++i){
            mul = mul * 10;
        }
        if(mul > 100000000 && que[front] > 2)
            return 0;
        result+=(que[front]*mul);
        front++;
        mul = 1;
    }
    //溢出情况
    if(result > 2147483647 || result < -2147483648)
        return 0;
    result+=que[rear];
    if(flag == 1)
        return result;
    else
        return -1*result;
}
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页