LeetCode刷题之Reverse Integer

Problem

Reverse digits of an integer.

Example:x = 123, return 321
Example:x = -123, return -321

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

My solution

public class Solution {
    int[] number = new int[50];

    public int reverse(int x) {
        int i = 0;
        while (x != 0) {
            number[i] = x % 10;
            x /= 10;
            i++;
        }
        int count = i, r = 0;
        long result = 0;
        for (i = 0; i < count; i++) {
            result += number[i] * (long)Math.pow(10, count - i - 1);
        }
        if (result >= Integer.MIN_VALUE && result <= Integer.MAX_VALUE) {
            r = (int) result;   
        } else {
            return 0;
        }
        return r;
    }
}
My Solution Update

public class Solution {

    int[] queue = new int[100];
    int head = -1, tail = -1;

    public int reverse(int x) {
        long result = 0;

        while (x != 0) {
            ++tail;
            queue[tail] = x % 10;
            x = x / 10;
        }
        while (head != tail) {
            ++head;
            result = result * 10 + queue[head];
        }
        return (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) ? 0 : (int)result;
    }
}
Great Solution

public int reverse(int x) {
    long answer = 0;
    while(x != 0) {
      answer = 10 * answer + x % 10;
        x /= 10;
    }
    return (answer > Integer.MAX_VALUE || answer < Integer.MIN_VALUE) ? 0 : (int) answer;
}

你可能感兴趣的:(LeetCode刷题之Reverse Integer)