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.

(1)思想1:设立一个falg=1,判断x<0,则令flag=-1;然后仍然是将数字转换成字符串,进行str[i] 与 str[len-1-i] 的一个互换,互换完成之后再将字符串转化成数字,此时需要注意的是:数字的范围是-2^32 ~ 2^32-1,所以必须对转换前和转换后的数字均进行判断,在这个范围内,则返回 flag*转换后的数字,否则返回0。

C++:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         int flag=1;
 5         if(x<0)
 6             flag=-1;
 7         string str=to_string(abs(x));
 8         int len=str.size();
 9         for(int i=0;i<len/2;i++)
10         {
11             char c=str[i];
12             str[i]=str[len-1-i];
13             str[len-1-i]=c;
14         }
15         long int result = flag*atol(str.c_str());
16         if(x>pow(2,31)-1 || x<-1*pow(2,31) || result>pow(2,31)-1 || result<-1*pow(2,31))
17             return 0;
18         return result;
19     }
20 };

 

posted @ 2017-12-15 10:19  西瓜刀刀刀  阅读(122)  评论(0编辑  收藏  举报