首页 > 其他 > 详细

LeetCode7 Reverse Integer

时间:2016-08-03 23:28:22      阅读:310      评论:0      收藏:0      [点我收藏+]

题意:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

 

分析:

思路很简单,注意特殊情况如10,100等和int溢出情况即可;

开始采用的是用一个数组把各位先存起来,再以此乘以相应的系数组成结果,但是这样写代码冗长而且费空间;

直接采用一个while循环即可;

代码1:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         long long result = 0;
 5         while (x != 0) {
 6             int temp = x % 10;
 7             x /= 10;
 8             result = result * 10 +  temp;
 9             if (result > 0x7FFFFFFF || result < -0x7FFFFFFF) {
10                 return 0;
11             }
12         }
13         return result;
14     }
15 };

 

查看讨论区,发现有一种不用0x7FFFFFFF判断的实现方式,作为参考;

代码2:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         int result = 0;
 5         while (x != 0) {
 6             int temp = x % 10;
 7             x /= 10;
 8             int newResult = result * 10 +  temp;
 9             if ( (newResult - temp) / 10 != result) {
10                 return 0;
11             }
12             result = newResult;
13         }
14         return result;
15     }
16 };

 

LeetCode7 Reverse Integer

原文:http://www.cnblogs.com/wangxiaobao/p/5734707.html

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