(C++練習) 7. Reverse Integer


題目 :

Given a 32-bit signed integer, reverse digits of an integer.

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.

大意 :

逆轉一個intege數字, 包含正負號, note 有提示要小心 超出邊界值。

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4 
 5         try
 6         {
 7             bool isNeg = x > 0 ? true : false;
 8             int lastDigit;
 9             int reverse = abs(x);
10             int res = 0;
11             while (reverse)
12             {
13                 if (res > 214748364 || 
14                     res < -214748364 ||
15                     (res == 214748364 && x % 10 > 7) ||
16                     (res == -214748364 && x % 10 < -8))
17                 {
18                     return 0;
19                 }
20                 lastDigit = reverse % 10;
21                 res = res * 10 + lastDigit;
22                 reverse = reverse / 10;
23             }
24 
25             if (isNeg)
26                 return res;
27             else
28                 return res * -1;
29         }
30         catch (exception e)
31         {
32             return 0;
33         }
34 
35     }
36 };

优质内容筛选与推荐>>
1、1-1Hellow,World!
2、对脑残的看法
3、MySQL权限分配
4、hdu 5661贪心二进制
5、命令行下文件名空格的处理


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号