首页 > 其他 > 详细

整数反转

时间:2019-10-10 01:06:35      阅读:123      评论:0      收藏:0      [点我收藏+]

给出一个 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         }

 

整数反转

原文:https://www.cnblogs.com/HYJ0201/p/11645092.html

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