首页 > 其他 > 详细

7. Reverse Integer

时间:2017-12-31 18:01:33      阅读:223      评论:0      收藏:0      [点我收藏+]

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

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

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