[LeetCode] Reverse Integer [8]

題目

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

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;
    }
};
------------------------------ 我是華麗的分割線-----------------------------------------
如果你覺得本篇對你有收穫,請幫頂。

另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.
你可以搜索公衆號:swalge 或者掃描下方二維碼關注我

(轉載文章請註明出處: http://blog.csdn.net/swagle/article/details/28721377 )

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章