Reverse Integer

题目:Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click to show spoilers. 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;
    }
}
这个答案比较简洁,发现自己已经会用一些比较麻烦的办法。但是这个方法没有考虑溢出

  1. int reverse(int x,bool &flag) {//flag means if the result is overflow  
  2.     int signal=1;  
  3.     if (x<0)  
  4.     {  
  5.         signal=-1;  
  6.     }  
  7.     int temp,ret=0,newv=0;  
  8.     while(x!=0)  
  9.     {  
  10.         temp = x%10;  
  11.         x = x/10;  
  12.         if (x!=0)  
  13.         {  
  14.             newv = newv*10 + temp;  
  15.         }  
  16.         else//last bit may overflow  
  17.         {  
  18.             if (signal<0)  
  19.             {  
  20.                 if ( 10*newv + temp >= 0)  
  21.                 {  
  22.                     flag = false;  
  23.                     ret = -1;  
  24.                     return ret;  
  25.                 }  
  26.                 ret = 10 * newv + temp;  
  27.             }  
  28.             else  
  29.             {  
  30.                 if ( 10*newv + temp <= 0)  
  31.                 {  
  32.                     flag = false;  
  33.                     ret = -1;  
  34.                     return ret;  
  35.                 }  
  36.                 ret = 10 * newv + temp;  
  37.             }  
  38.               
  39.         }  
  40.     }  
  41.     return ret;  
  42. }  
只有最后一次计算时有可能产生溢出,对结果进行判断即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值