1. 程式人生 > >leetcode題解 7.Reverse Integer

leetcode題解 7.Reverse Integer

ron 範圍 color easy 語句 sum public 反轉 lee

題目:

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