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 };