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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题目大意:输入一个整数,输出其反转数。
理 解:根据题目的例子和提示,在实现反转时要考虑三个问题。将整数转换为字符串可以通过字符串函数得到整数“长度”。使用栈保存每个数字,方便逆转。
1.若是 负数,则先转换为正数,输出时加上“-”号。(注意:若输入为INT_MIN是无法转换为正整数的,应单独判断,它的反转数为0)
2.若是 末尾为0的数。在出栈时记录末尾为0的数字个数,并排除。
3.若是 超过整数可表达范围的数(这是最难的),逆转时,每计算一次,我将计算结果/10(取模10则不会超过能表达的最大范围)与INT_MAX/10比较。最后处理判断个位数是否超过范围。
附注:使用stack<char>代替stack<int>可以很大地提高。
代 码 C++:
class Solution { public: int reverse(int x) { if(x==INT_MIN || x==0) return 0; int val,flag=0,n,i,front,zeroCount=0; string str; stack<char> sta; if(x<0){ val = x*(-1); flag = 1; } else val = x; str = to_string(val); n = str.length(); for(i=n-1;i>=0;i--){ front = val/pow(10,i); val = val%(int)(pow(10,i)); sta.push(front); } while(sta.top()==0){ zeroCount++; sta.pop(); } n = n - zeroCount; if(n>10) return 0; if(n==1 && flag==0) return sta.top(); if(n==1 && flag==1) return (-1)*sta.top(); val = 0; for(i=n-2;i>=0;i--){ front = sta.top(); sta.pop(); val = val + front*pow(10,i); if(val>INT_MAX/10) return 0; } front = sta.top(); sta.pop(); if(val == INT_MAX/10){ if(front==8 && flag==1) return INT_MIN; if(front==8||front==9) return 0; } val = val*10 + front; if(flag==1) val = val*(-1); return val; } };