7. 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: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解答

水题,取余,考虑不要越界就可以,我用的这个方法有点蠢,待改进。

class Solution {
public:
    int reverse(int x) {
        if (x == -2147483648) {
            return 0;
        }
        int xx = abs(x);
        vectors;
        int flag = int(xx == x);
        while (abs(xx) > 0) {
            if (s.size() == 0 && xx % 10 == 0) {
                xx /= 10;
                continue;
            }
            s.push_back(xx % 10);
            xx /= 10;
        }
        vector::iterator it;
        int k = s.size() - 1;
        int y = 0;
        int danger = s.size() >= 10 ? 1 : 0;
        int mz[10] = {6, 4, 6, 3, 8, 4, 7, 4, 1, 2};
        int mf[10] = {7, 4, 6, 3, 8, 4, 7, 4, 1, 2};
        int m;
        for (it = s.begin(); it < s.end(); it++) {
            if (flag) {
                m = mz[k];
            }
            else {
                m = mf[k];
            }
            if (danger) {
                if (m < *(it)) {
                    return 0;
                }
                else if (m > *(it)) {
                    danger = 0;
                }
            }
            y += *(it) * pow(10, k--);
        }
        return y * pow(-1, flag + 1);
    }
};

题外话

因为申请了一个迭代器,空间复杂度略高。(待续)

你可能感兴趣的:(7. Reverse Integer)