leetcode------Reverse Integer

标题:Reverse Integer
正确率:34.8%
难度简单

Reverse digits of an integer.

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

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

这个题是我感觉我最能做出来的一道!但是我却用了很长时间。。主要卡在了越界问题上面,

1、越界的主要问题是传进来的值一定不越界的,但是翻转过后的数值会出现越界的问题。

2、int的界问题,由于我随便在网上查了下int的界被网上的错误答案所迷惑了。java int的范围应该是-2147483648   到2147483647  下界的绝对值是比上界的绝对值大的

所以判断越界还是很重要的!!

关键是怎么能快捷。

特别是取余保存这个地方还有更更加简介的方式

y=y*10+x%10;

然后就是判断正负数了。

这个题总体不难,不用讲太多的逻辑直接看代码就行:

 1 public class Solution {
 2     public int reverse(int x) {
 3         int negative=-1;
 4         boolean flag=false;
 5         if(x<10&&x>-10) return x;
 6         if(x==0) return 0;
 7         if(x<0){
 8             x*=-1;
 9             flag=true;
10         } 
11         long y = x%10;  
12           if(y<0)return 0;
13         while( x/10 != 0 ) {  
14             x /= 10;  
15             y *= 10;  
16             y += x%10;  
17         }
18        if(y>(Integer.MAX_VALUE)) return 0;
19         if(flag==true){
20             return (int) (negative*y);
21         }
22         else
23         return (int) y;
24     
25     }
26 }

 

转载于:https://www.cnblogs.com/pkuYang/p/4160638.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值