題目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
解題思路
顛倒一個整數中數字的位置,哈哈,類似翻轉字符串一樣,只不過整數需要計算,需要考慮溢出,其他無而。寫出代碼不難,只是溢出的時候怎麼辦,我這裏是按照返回-1處理的,在leetcode上可以AC。
代碼實現:
class Solution {
public:
int reverse(int x) {
int sign = 1;
if(x < 0) sign = -1;
int ret =0;
while(x!=0){
ret = ret*10 + abs(x%10)*sign;
x /= 10;
}
if((x>0 && ret <0) && (x<0 && ret>0)) return -1;
return ret;
}
};
如果你覺得本篇對你有收穫,請幫頂。
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.