LeetCode數學類(一)

今天又刷了兩道數學類的easy題,雖然是easy題,但還是有點體會。

題目一

Reverse digits of an integer.

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

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?

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.

分析

剛開始的時候我是採取了先判斷x的正負,根據顛倒之後是否變號來判斷是否溢出的,結果證明這種方法有些case通不過。看了別人的代碼才知道,原來可以通過定義long long int來解決這個問題,受教了。

代碼

class Solution {
public:
    int reverse(int x) {
        long long int result=0;
        while(x!=0){
            result=result*10+x%10;
            x=x/10;
        }
        return (result<INT_MIN || result>INT_MAX) ? 0 : result;
    }
};

題目二

Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.

分析

這道題是讓判斷一個數是不是迴文數的,很明顯。負數是沒有迴文數的,能整除10的數字也是沒有迴文數的。剛開始我是想直接把一個數顛倒過來判斷是否相等來計算的。結果發現比較慢,後來想到了其實並沒必要全部判斷,可以以顛倒到兩者相等爲分界點,也就是代碼一中的(x>result)這一句話結束循環時x<=result。相等的情況就是1221這種迴文數,不等的就是12321這種迴文數。所以代碼一寫的很嚴謹。代碼二是一種更高效的代碼,它主要是採取了一種一位位比較,只要有一位不相等,立馬就返回的方法。在某些不是迴文數的判斷上會比方法一快速。其中我也發現了LeetCode上的一個問題,相同的代碼,每次運行的時間卻相差比較大。如下圖所示。

這裏寫圖片描述

代碼一

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0||(x!=0&&x%10==0)) 
            return 0;
        int result=0;
        while(x>result){
            result=result*10+x%10;
            x=x/10;
        }
        return (x==result)||(x==result/10);
    }
};

代碼二

class Solution {
public:
    bool isPalindrome(int x){
       if(x<0) {
            return false;
        }
        int div = 1;
        while(div <= x/10)
            div *= 10;
        while(x>0){
            if(x/div != x%10)
                return false;
            x = (x%div)/10;
            div /= 100;
        }
        return true;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章