求数字的逆序表示

来源:互联网 发布:北京黑马程序员 编辑:程序博客网 时间:2024/05/17 22:00

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

一般的实现方法:鲁棒性不强,很多特殊情况没有考虑。

public class Solution {    public int reverse(int x) {        int rst = 0;        while(x != 0){            rst = rst * 10 + x % 10;            x = x / 10;        }        return rst;    }}
上述代码解决了负号问题,但是如果数字倒序后溢出,似乎没有考虑到这些情况。不具鲁棒性。也是很多人容易的犯错。应该继续修改代码,完善代码功能。

       考虑到上述等特殊情况,可以先使用字符串来表示数字,然后再把之逆序,最后再以数字的形式输出。实现代码如下:

public class Solution {    public int reverse(int x){    String strX = Integer.toString(x);    int len = strX.length();    StringBuffer dest = new StringBuffer(len);    if(x>=0){        for(int i = len -1; i >= 0 ; i--){            dest.append(strX.charAt(i));        }    }    else{        dest.append('-');        for(int i = len -1; i >= 1 ; i--){            dest.append(strX.charAt(i));        }    }
<span style="white-space:pre"></span>return Integer.parseInt(dest.toString());}}
讨论:

代码最后的语句:return Integer.parseInt(dest.toString());如果此时字符串表示溢出,会抛出一个异常。这似乎也不没有解决溢出问题。实际上,可以根据实际需求来提供解决方案。1.如果溢出则抛出异常。 2.使用一个extra parameter来表示数字是否溢出。 3.可以依次打印字符串中的每一个字符,这样即使数字溢出,也能表示出它的逆序。

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 喜欢我的人太多怎么办 假如战争今夜打响我们该怎么办 约客户客户说忙怎么办 第一天来姨妈痛怎么办 痛经痛的很厉害怎么办 工作第一天被辞怎么办 第一天练车紧张怎么办 到新公司第一天怎么办 我妈上班别人欺负怎么办 欺负别人他妈来找了怎么办 家人都欺负我妈怎么办 人老了日不动了怎么办? 日照职业技术学院公租房怎么办留宿 眼镜上沾了胶水怎么办 近视镜片刮花了怎么办 墨镜镜片磨花了怎么办 邻居养狗味道大怎么办 邻居不让养狗了怎么办 养狗地板有味道怎么办 狗狗嘴巴被大狗咬肿了怎么办 花了钱心里难受怎么办 狗在屋里有味道怎么办 养狗家里有异味怎么办 养狗房子有味道怎么办 狗身上有腥臭味怎么办 狗狗不想养了怎么办 药流2天后没出血怎么办 药流当天血多怎么办 怀孕四十天不想要怎么办 人流后出血量大怎么办 药流一直不出血怎么办 药流一直不见红怎么办 药流12天还流血怎么办? 把别人车刮了怎么办 车划掉漆了怎么办啊 倒车时碰了车怎么办 车头掉了一点漆怎么办 新买的车被刮了怎么办 白色车车头漆掉了一小块怎么办 临时牌照丢了1张怎么办 临牌遗失了一张怎么办