LeetCode Online Judge 题目C# 练习 - Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

 1         public static bool PalindromeNumberRec(int x)
 2         {
 3             return isPalindrome(x, ref x);
 4         }
 5 
 6         public static bool isPalindrome(int x, ref int y)
 7         {
 8             if(x < 0) return false;
 9             if(x == 0) return true;
10 
11             if(isPalindrome(x / 10, ref y) && (x % 10 == y % 10))
12             {
13                 y /= 10;
14                 return true;
15             }
16             else
17                 return false;
18         }

代码分析:

  递归的做法,先递归到最底,然后回溯头一位跟尾一位比较。

  例如:“12321”

  “1232”, “12321”

    -- “123”, “12321”

      -- “12”, “12321”

        -- “1”, “12321”

          -- “0”, “12321” true;递归到这里最底

        -- “1”, “12321” 比较 1 % 10 == 12321 % 10,y /= 10, 返回 true;

      -- “12”, “1232” 比较 12 % 10 == 1232 % 10,y /= 10, 返回 true;

    -- "123", "123" 比较 123 % 10 == 123 % 10,y /= 10, 返回 true;

  -- “1232”, “12” 比较 1232 % 10 == 12 % 10,y /= 10, 返回 true;

 -- “12321”, “1” 比较 12321 % 10 == 1 % 10, y /= 10, 返回true;

 1         public static bool PalindromeNumber(int x)
 2         {
 3             if (x < 0)
 4                 return false;
 5 
 6             int div = 1;
 7             while (x / div >= 10)
 8             {
 9                 div *= 10;
10             }
11 
12             while (x != 0)
13             {
14                 int l = x / div;
15                 int r = x % 10;
16                 if (l != r)
17                     return false;
18                 x = (x % div) / 10;
19                 div /= 100;
20             }
21 
22             return true;
23         }

代码分析:

  迭代的做法,先把x 的位数找到。x = 12321, div = 10000;

  然后再 l = x / div; r = x % 10; 分别得到头尾,比较相同后 x = ( x % div) / 10; 去头去尾, div /= 100;

  

  看题目要求negative number算不算,如果算,先做一次绝对值就好了,LEETCODE上的TEST CASE negetive nubmer是不算的。