首页 > 其他 > 详细

Reverse Integer

时间:2014-03-12 05:52:48      阅读:474      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
1     int reverse(int x) {
2         int y=0;
3         while(x)
4         {
5             y=y*10+x%10;
6             x=x/10;
7         }
8         return y;
9     }
bubuko.com,布布扣

我试过了,不用区分是正数还是负数,他们的计算方法是一样的

上面的代码虽然AC了,不过题上spoilers说的好,有可能会溢出,这个上述代码并没有考虑

32位,1位符号位,剩下31位,表示范围 From ?2,147,483,648 to 2,147,483,647, from ?(231) to 231 ? 1

bubuko.com,布布扣
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 shouldyou 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).
bubuko.com,布布扣

 由于传进来的参数时int,参数本身不会溢出,但是逆转之后就可能会溢出了,关键是怎么判断逆转之后会溢出?

我在codeblocks中试了一下,正数溢出之后会变成负数,负数溢出之后会变成正数

下面的代码是写着玩的,因为函数返回值是int,所以即使用 long long 存储溢出的也不行的

bubuko.com,布布扣
 1     int reverse(int x) {
 2         int v=x;
 3         int y=0;
 4         while(x)
 5         {
 6             y=y*10+x%10;
 7             x=x/10;
 8         }
 9         //判断是否溢出
10         //正数溢出为负数,负数溢出为正数
11         if(v<=0&&y<=0||v>=0&&y>=0)//我觉得这么比x*y>0算的快一些
12             return y;
13         else
14         {
15             long long z=0;
16             while(v)
17             {
18                 z=z*10+v%10;
19                 v=v/10;
20             }
21             return z;   // 额,好吧,人家的函数返回值类型也是int型的
22         }
23     }
bubuko.com,布布扣

Reverse Integer,布布扣,bubuko.com

Reverse Integer

原文:http://www.cnblogs.com/crane-practice/p/3594102.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!