整数反转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer

 1 public int Reverse(int x)
 2         {
 3             int num = 0;
 4             bool isFlag = true;
 5 
 6             if (x < 0)
 7             {
 8                 x = x * -1;
 9                 isFlag = false;
10             }
11             while (x > 0)
12             {
13                 int a = x % 10;
14                 if ((a == 0 && num != 0) || a != 0)
15                 {
16                     int b = num * 10;
17                     if (b / 10 != num)
18                     {
19                         num = 0;
20                         break;
21                     }
22                     num = num * 10 + a;
23 
24                 }
25                 x = x / 10;
26             }
27             if (!isFlag)
28             {
29                 num = num * (-1);
30             }
31             return num;
32         }

 

posted @ 2019-10-09 23:26  *飞*  阅读(132)  评论(0编辑  收藏  举报