Class Solution{ publicstaticintreverse(int n) { if (n > Integer.MAX_VALUE || n < Integer.MIN_VALUE) { return0; } Strings= String.valueOf(n); if (n < 0) { s = s.substring(1, s.length()); char[] array = s.toCharArray(); Stringreverse="-"; for (inti= array.length - 1; i >= 0; i--) { reverse += array[i]; } s = reverse; } else { char[] array = s.toCharArray(); Stringreverse=""; for (inti= array.length - 1; i >= 0; i--) { reverse += array[i]; } while (reverse.length() > 1 && reverse.charAt(0) == '0') { reverse = reverse.substring(1, reverse.length()); } s = reverse; } inti=0; try { i = Integer.parseInt(s.toString().trim()); } catch (Exception e) { return0; } return i; } }
下面是Python的代码:
classSolution: defreverse(self, x: int) -> int: if x >= 0: res = int(str(x)[::-1]) else: res = int('-' + str(x)[:0:-1]) return res if -2147483648 <= res <= 2147483647else0