LeetCode:Palindrome Number

1097 ワード

問題の説明:
Determine whether an integer is a palindrome. Do this without extra space.
考え方:
1、桁数を求める;
2、取り出し数の1位と最後の位を比較し、同じであれば、1位と最後の位を同時に削除し、base次元を100に下げ、新しい数の頭と尾を比較して循環する.待たない場合はfalseに戻ります.
コード:
コード1
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)  return false;
        if(x == 0)  return true;
        int temp = x;
        int sum = 0;
        while(x > 0){
            sum = sum * 10 + temp % 10;
            temp /= 10;
        }
        return (sum == temp)?true:false;
    }
};
タイムアウト、機能は実現できますがACはできません.
コード2
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)  return false;
        if(x == 0)  return true;
        int div = 1;
        while(x / div >= 10)
            div *= 10;
        while(x != 0){
            int leftdigit = x / div;
            int rightdigit = x % 10;
            if(leftdigit != rightdigit)   return false;
            x = (x % div) / 10;
            div /= 100;
        }
        return true;
    }
};