第三週Reverse Integer反轉數字

Reverse Integer反轉數字

Leetcode algorithms problem 7:Reverse Integer

  • 問題描述

    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?
    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
    Note:
    The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

  • 思路

    每次乘以10後再從尾取值,再將x自除即可,重點在判斷溢出
    將返回值設爲long long屬性,避免在反轉時過大超過int範圍而直接變爲-2147483647值,導致最後輸出爲該值。

代碼

class Solution {
public:
    int reverse(int x) {
         int a = 0;
         long long result = 0;
         while( x != 0){
            result = result*10 + x % 10;
            x = x/10;
            if( result > 2147483647 || result < -2147483647) {
                 return a;
            }
        }
        return (int) result;
    }
};

時間複雜度: O(logn)
空間複雜度: O(1)


疑難

判斷是否溢出 的return 語句,一開始直接使用return 0,結果一直在溢出的test通不過,換成return一個值爲0的變量就通過了。尚不清楚原因

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