翻转整数

刚刚做了这题,发现自己数据结构都白学了一样,根本就没想起来用栈

题目如下

反转整数—Reverse Integer

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.

我看到题目的第一反应就是,互换位置不就好了,于是没多想就开始各种类型转换,代码如下

 1 class Solution {
 2     public int reverse(int x) {
 3         //去掉符号
 4         if(x<0){ x = 0 - x; }
 5         //将int转换为String
 6         String str1 = Integer.toString(x);
 7         //将String转换为char[]
 8         char str2[] = str1.toCharArray();
 9         //交换位置
10         for(int i=0,j=str2.length-1;i<j;i++,j--){
11             char temp=0;
12             temp=str2[i];
13             str2[i]=str2[j];
14             str2[j]=temp;
15         }
16         //将char[]转换为String
17         String str3 = new String(str2);
18         //将String转换为int
19         return Integer.parseInt(str3);
20     }
21 }

int String char[ ] 之间的转换到时都用了个遍,提交后才发现没能通过,完全忘记了题目要求的数值范围,简单粗暴加了异常处理后,在eclipse进行测试又发现,忘记负号问题了,更改后最终提交通过的代码如下

但是这个大概真的是最最简单粗暴的方法了吧,leetcode给出的解决方案用到了栈,栈的概念我还记得,但是具体操作还要再看看

 1 class Solution {
 2     public int reverse(int x) {
 3     try{    
 4         //去掉符号
 5         int sign = 1;
 6         if(x < 0){ x = 0 - x; sign = -1;}
 7         //将int转换为String
 8         String str1 = Integer.toString(x);
 9         //将String转换为char[]
10         char str2[] = str1.toCharArray();
11         //交换位置
12         for(int i=0,j=str2.length-1;i<j;i++,j--){
13             char temp=0;
14             temp=str2[i];
15             str2[i]=str2[j];
16             str2[j]=temp;
17         }
18         //将char[]转换为String
19         String str3 = new String(str2);
20         //将String转换为int
21         //int b = Integer.parseInt(str3);
22         return sign*Integer.parseInt(str3);
23     }catch(Exception e){
24         return 0;
25     }
26     }
27 }

猜你喜欢

转载自www.cnblogs.com/zyx210/p/9267841.html