LeetCode——reverse-integer

Q: integer x will be given of the flip. Example 1: x = 123, returns 321 cases 2: x = -123, -321 return

Have you thought about the following questions? If the last bit integer is zero, then the output should be? For example, the integer may overflow flip 10,100 Have you noticed it? Assuming that the input is a 32-bit integer, then flip 10,000,000,003 will overflow, how would you deal with such a sample? Throw an exception? They do well, but if it does not allow an exception is thrown? So you have to redesign the function (such as adding an additional parameter).

A: ...... with string is not a little better?

    public int reverse(int x) {
        String s = Integer.toString(x);
        char[] c = s.toCharArray();
        if (c[0] == '-') {
            swapIn(c, 1, c.length - 1);
        } else {
            swapIn(c, 0, c.length - 1);
        }
        String s1 = new String(c);
        int result = 0;
        try {
            result = Integer.parseInt(s1);
        } catch (Exception e) {
            return 0;
        }
        return result;
    }

    private void swapIn(char[] c, int start, int end) {
        while (start < end) {
            char temp = c[start];
            c[start] = c[end];
            c[end] = temp;
            start++;
            end--;
        }
    }

Guess you like

Origin www.cnblogs.com/xym4869/p/12652435.html