leetcode题解 7.Reverse Integer

Posted wangziyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode题解 7.Reverse Integer相关的知识,希望对你有一定的参考价值。

题目:

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

Example 1:

Input: 123
Output:  321

 

Example 2:

Input: -123
Output: -321

 

Example 3:

Input: 120
Output: 21

 

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

这个题目是一个easy的题目,但是细节要注意,第一点要注意记得处理负数的情况,

第二点就是记得看Note,Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

就是超过int的范围了就需要返回0。这一点非常重要,因为你要判断的是可能反转后会溢出,那么需要注意的就是

需要用一个long long来存储答案ans。判断使用的语句就是:

if(ans>INT_MAX||ans<INT_MIN)
            return 0;

啦啦啦!

代码如下:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         long long ans=0;
 5         bool isLittle=false;
 6         if(x<0)
 7         {
 8             x=-x;
 9             isLittle=true;
10         }
11         while(x>0)
12         {
13             int num=x%10;
14             ans=ans*10+num;
15             x=x/10;
16         }
17         if(ans>INT_MAX||ans<INT_MIN)
18             return 0;
19         if(isLittle)
20             return -ans;
21         else return ans;
22     }
23 };

 



以上是关于leetcode题解 7.Reverse Integer的主要内容,如果未能解决你的问题,请参考以下文章

7. 反转整数 [leetcode 7: Reverse Integer]

7. 反转整数 [leetcode 7: Reverse Integer]

#Leetcode# 7. Reverse Integer

[LeetCode #7] Reverse integer

LeetCode 7 Reverse Integer

[leetcode]7-Reverse Integer