码迷,mamicode.com
首页 > 其他好文 > 详细

整数反转

时间:2019-10-09 23:55:53      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:reverse   环境   数字   amp   一个   pre   注意   tco   存储   

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

 

整数反转

标签:reverse   环境   数字   amp   一个   pre   注意   tco   存储   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!