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

7. Reverse Integer

时间:2017-12-31 18:35:29      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:问题   class   cti   bsp   bit   lin   note   amp   ble   

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.

思路:用一个long型来解决overflow问题

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         long n=x;
 5         bool isActive;
 6         if(n<0)
 7         {
 8             n=-n;//将负数转化为正数来处理
 9             isActive=false;
10         }else{
11             isActive=true;
12         }
13         char arr[30];
14         int i=0;
15         while(n)
16         {
17             arr[i++]=n%10+0;
18             n=n/10;
19         }
20         long reverseN=0;
21         int j=0;
22         while(j<i)
23         {
24             reverseN=10*reverseN+arr[j++]-0;
25         }
26         if(!isActive)reverseN=-reverseN;//如果是负数,就变回负数
27         if(reverseN>INT_MAX || reverseN<INT_MIN)return 0;
28         else return reverseN;
29     }
30 };

 

7. Reverse Integer

标签:问题   class   cti   bsp   bit   lin   note   amp   ble   

原文地址:https://www.cnblogs.com/jeysin/p/8158033.html

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