Reverse Integer

2019-05-25 22:56:13 浏览数 (1)

1. Description

2. Solution

  • Two loops
代码语言:javascript复制
class Solution {
public:
    int reverse(int x) {
        if(x == 0 || x == INT_MIN) {
            return 0;
        }
        int remainder = 0;
        int y = abs(x);
        queue<int> number;
        while(y) {
            remainder = y % 10;
            number.push(remainder);
            y /= 10;
        }
        int result = 0;
        while(!number.empty()) {
            if((INT_MAX - number.front()) / 10 < result) {
                return 0;
            }
            result = result * 10   number.front();
            number.pop();
        }
        return x == abs(x)?result:-result;
    }
};
  • One loop
代码语言:javascript复制
class Solution {
public:
    int reverse(int x) {
        if(x == 0 || x == INT_MIN) {
            return 0;
        }
        int y = abs(x);
        int result = 0;
        int remainder = 0;
        while(y) {
            remainder = y % 10;
            if((INT_MAX - remainder) / 10 < result) {
                return 0;
            }
            result = result * 10   remainder;
            y /= 10;
        }
        return x == abs(x)?result:-result;
    }
};

0 人点赞