1. 程式人生 > >LeetCode 9. 迴文數 Palindrome Number(C語言)

LeetCode 9. 迴文數 Palindrome Number(C語言)

題目描述:

判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。

示例 1:

輸入: 121
輸出: true

示例 2:

輸入: -121
輸出: false
解釋: 從左向右讀, 為 -121 。 從右向左讀, 為 121- 。因此它不是一個迴文數。

示例 3:

輸入: 10
輸出: false
解釋: 從右向左讀, 為 01 。因此它不是一個迴文數。

進階:

你能不將整數轉為字串來解決這個問題嗎?

題目解答:

方法1:完全翻轉

完全求出翻轉之後的數字,比較兩數字是否相同即可,但效率較低。執行時間116ms左右,程式碼如下。

bool isPalindrome(int x) {
    if(x < 0)
        return false;
    if(x == 0)
        return true;
    int result = 0, before = x;
    while(x) {
        result = result * 10 + x % 10;
        x /= 10;
    }
    return result == before;
}

方法2:部分翻轉

考慮只翻轉到中點位置,判斷兩個數字是否相同,或者result除以10之後是否相同。相對於方法1,除法和取餘的次數減少一般左右,故執行更快。注意

整10倍數字,其末尾為0,故必定不是迴文數。執行時間112ms,程式碼如下。

bool isPalindrome(int x) {
    if(x == 0)
        return true;
    if(x < 0 || x % 10 == 0)
        return false;
    int result = 0;
    while(x > result) {
        result = result * 10 + x % 10;
        x /= 10;
    }
    return (result == x || result / 10 == x);
}