LeetCode(9)PalindromeNumber

2380 ワード

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.
この問題、巨汗、何度も提出してやっと成功して、私の基本的な考え方は循環体の中で、絶えず第i位と最後から第i位を比較して、最も中間の1つの数字(奇数の数字を入力します)あるいは最も中間の2つの数字(偶数の数字を入力します)に出会うまでいくつかの特殊な判断を行います.注意すべきは、本題の問題は余分な空間を使うことができないことを要求しているので、文字列が回文であるかどうかを判断する前の問題の経験を借りることができません.
これらのcaseは前回の失敗をもたらしました.
     Input: 1001
     Output: false
     Expected: true
     Input: 1000110001
     Output: false
     Expected: true
     Input: 1020110201;
     Output: false
     Expected: true
修正された最終コードは次のとおりです.
class Solution {
public:
    bool isPalindrome(int x) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(x==INT_MIN)
            return false;
        if(x==0)
            return true;
        if(x<0)//    ,Online Judge            return false。
            return false;
            
        while(x){
            if((x<100)&&(x>10)&&(x%11==0))
                return true;
            if(x<10)
                return true;
            int count=0;
            int large_digit=x;
            int large_digit2=x;
            
            while(large_digit2>=100){
                large_digit2=large_digit2/10;
                count++;
            }
            large_digit=large_digit2/10;
            count++;
            int small_digit=x-x/10*10;
            int y=x/10;
            int small_digit2=y-y/10*10;
//            std::cout<

いつも自分がくどくど書いているような気がして、見ていると本当に不快です.ちょっと見てcomの参考答案は、とても優美で簡潔です.計算ヘッダを表す変数(div)を使用し、%10を使用して末尾を計算します.
bool isPalindrome(int x) {
  if (x < 0) return false;
  int div = 1;
  while (x / div >= 10) {
    div *= 10;
  }        
  while (x != 0) {
    int l = x / div;
    int r = x % 10;
    if (l != r) return false;
    x = (x % div) / 10;
    div /= 100;
  }
  return true;
}