1. 程式人生 > >LeetCode :C語言 9.迴文數

LeetCode :C語言 9.迴文數

迴文數簡而言之就是對稱的數(負數按題目要求不是),因為上一個題目是反轉整數很自然的就想到了直接反轉之後判斷。

bool isPalindrome(int x)
{
    int out = 0,in = x;
    int temp;
    if(x<0)
        return false;
    while(x)
    {   
        int temp = out*10 + x%10;
        x = x/10;
        out=temp;
    }
    if(out==in)
        return true;
    else
        return false;
}

執行是通過的,再看了答案後發現只需要反轉後半段數字即可(若為奇數,則將x/10後判斷)

bool isPalindrome(int x)
{

   if(x<0||x % 10 == 0 && x != 0)
        return false;
    
    int reverNum = 0;
    while(x>reverNum)
    {
        reverNum = reverNum*10 + x%10;
        x=x/10;
    }
    
    return (x==reverNum || x==reverNum/10);
}

收貨:做題的時候視野應該更廣闊,不能慣性地想問題。