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

leetcode题解 7.Reverse Integer

时间:2018-04-06 19:33:21      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:eal   inpu   class   一点   ble   rev   function   sed   which   

题目:

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

标签:eal   inpu   class   一点   ble   rev   function   sed   which   

原文地址:https://www.cnblogs.com/wangziyan/p/8728364.html

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