LeeCode(9) Palindrome Number C語言

題目:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

不轉換爲字符串

思路:
將int型數倒置,然後比較是是否相同,倒置的時候要是否越界。

代碼:

bool isPalindrome(int x){
    
    if (x<0)
    {
        return false;
    }
    
    bool res =false;
    int mod = 0;
    int con = x;
    double new =0;
    
    
    while (con >0)
    {
        mod = con %10;
        con =con/10;
        new =new *10 + mod;
    }
    
    if(x == new)
    {
        res = true;
    }
    
    return res;
}

效率:
效率還行,挺簡單的一個題目,應該還有其他解法。
LeeCode(9) 效率

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