LeetCode - Algorithms - 7. Reverse Integer

Java

1

自己做出来的naive solution,直接把整数转换成字符串,然后逆转字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public int reverse(int x) {
int r = 0;
if (x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return r;
}
String s = Integer.toString(x);
if (s!=null && !s.isEmpty()) {
String ss = "";
char c = 0;
if (x<0)
s = s.substring(1);
for(int i=s.length()-1;i>=0;i--) {
c = s.charAt(i);
ss += c;
}
if (x<0)
ss = '-'+ss;
System.out.println("ss="+ss);
try {
r = Integer.parseInt(ss);
} catch (NumberFormatException ex) {
r = 0;
}
}
return r;
}
}

Submission Detail

  • 1032 / 1032 test cases passed.

2

9. Palindrome Number ,提示Coud you solve it without converting the integer to a string? 发现人家的方法更直接利落,温故而知新,重新实现下,结果被卡在 java int out of range 的问题里,1534236469 逆序数超过Integer.MAX_VALUE 返回 1056389759,题目里就提示了 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. 最后想到不如把逆序数变量定义为 long类型,再判断是否超过2147483647(0x7fffffff, 2^31-1),再把long 安全地转换为int返回,java的long安全转换为int的小问题,google关键字 java long to int 参考了下 Safely casting long to int in Java 这样就ok了,在leetcode上运行通过。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int reverse(int x) {
if (x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return 0;
}
if (x==0) return 0;
int r = 0;
int remainder = 0;
long reverseNumber = 0L;
for(int t = x>0?x:-x; t>0; t/=10) {
remainder = t%10;
reverseNumber *= 10;
reverseNumber += remainder;
}
if (reverseNumber>Integer.MAX_VALUE)
r = 0;
else
r = Long.valueOf(reverseNumber).intValue();
if (x<0)
r *= -1;
return r;
}
}

Submission Detail

  • 1032 / 1032 test cases passed.
  • Runtime: 21 ms
  • Your runtime beats 97.62 % of java submissions.