LeetCode——Reverse Integer

来源:互联网 发布:windows 保存窗口大小 编辑:程序博客网 时间:2024/05/16 18:01

Reverse Integer


Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

public class Solution {    public int reverse(int x) {       String tmp = new String();String tmp_2 = new String();tmp = ((Integer) x).toString();if (tmp.charAt(0) == '-') {for (int i = tmp.length() - 1; i > 0; i--)tmp_2 = tmp_2 + tmp.charAt(i);tmp = "-" + tmp_2;} else {for (int i = tmp.length() - 1; i >= 0; i--)tmp_2 = tmp_2 + tmp.charAt(i);tmp = tmp_2;}return Integer.parseInt(tmp);      }}

Submission Result: Runtime Error

Runtime Error Message:Line 17: java.lang.NumberFormatException: For input string: "7463847412"Last executed input:2147483647



 

返回结果超出int整数范围,应该考虑转化之后数值大小的边界检查

原先的思路是用穷举法对结果检查,试了很多次都没有pass;一怒之下,直接用try/catch捕捉异常,搞定。

Java代码:

public class Solution {    public int reverse(int x) {       String tmp = new String();String tmp_2 = new String();tmp = ((Integer) x).toString();if (tmp.charAt(0) == '-') {for (int i = tmp.length() - 1; i > 0; i--)tmp_2 = tmp_2 + tmp.charAt(i);tmp = "-" + tmp_2;} else {for (int i = tmp.length() - 1; i >= 0; i--)tmp_2 = tmp_2 + tmp.charAt(i);tmp = tmp_2;}        try{Integer.parseInt(tmp);}catch(Exception e){return 0;}return Integer.parseInt(tmp);      }}


0 0
原创粉丝点击