1. 程式人生 > >leetcode -- 7. Reverse Integer runtimes beats 100.00% of java submissions

leetcode -- 7. Reverse Integer runtimes beats 100.00% of java submissions

題目描述

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.

AC程式碼

class Solution {
    public int reverse(int x) {
        int negative = 1;
        if(x < 0) {
        	negative = -1;
            x = x * -1;
        }
        char[] charIntMax = String.valueOf(Integer.MAX_VALUE).toCharArray();
        char[] chars = String.valueOf(x).trim().toCharArray()
; int low = 0, high = chars.length - 1; while(low < high){ char tmp = chars[low]; chars[low] = chars[high]; chars[high] = tmp; low++; high--; } if(chars.length < charIntMax.length) return Integer.
valueOf(new String(chars)) * negative; low = 0; high = charIntMax.length - 1; while(low <= high){ if(charIntMax[low] > chars[low]) return Integer.valueOf(new String(chars)) * negative; if(charIntMax[low] < chars[low]) return 0; low++; } return 0; } }