LeetCode No.9 Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
这题又是Vaguely stated。点开Spoiler,问你负数如何处理?我哪知道你怎样才判对。去discuss看看,才发现负数一律不算palindrome。
一看integer,马上想到overflow。想了想,没太多需要考虑的了。
题目第二句话把我坑了好久。不允许使用额外空间啊擦。那就只能各种digit manipulation了。最终吭哧吭哧还是写出来了个。还蛮有成就感的。
思路如下:
1,负数返回假,一位数返回真,两位数如果是11的倍数返回真。三位数如果高位低位相同返回真。其实三位数不用单独判断。
2,其余的数字,最高位(HIGH)如果和最低位(LOW)相同,截断(REMAIN),递归调用自己判断剩余的数字。但是有个问题就是0开头的问题。如果截断之后的数字是0开头可能导致结果错误,所以这里稍微处理一下,如果次高位(SH)和次低位(SL)都是0,把他们都变成1就行。(一旦做加法就有可能溢出,所以程序中要处理溢出)
O(zero) space。代码如下。
#define NOD(x) ((int)log10(x) + 1) // Number of digits of x. #define POT(x) ((int)pow(10, NOD(x) - 1)) // The maximum power of ten it contains. POT(700) = 100, POT(2900) = 1000 #define HIGH(x) ((int)x / POT(x)) // Top digit. #define SH(x) ((int)(x / (POT(x) / 10)) % 10) // Second top digit. SH(1234) == 2. #define LOW(x) (x % 10) // Bottom digit. #define SL(x) ((x % 100) / 10) // Second bottom digit. SL(1234) == 3. #define REMAIN(x) ((int)(x - x / POT(x) * POT(x)) / 10) // The remaining number after trimming off the top and bottom digit. REMAIN(1234) == 23. #define TRIM(x) ((x + (int)(POT(x) / 10) + 10)) // In case the second top digit is zero, change those zeros to 1. class Solution { public: bool isPalindrome(int x) { if (x < 0) return false; else if (x < 10) return true; else if (x > 10 && x < 100) return !(x % 11); else if (x > 100 && x < 1000) return x % 10 == (x / 100); else if (x % 10 == 0) return false; else { if (HIGH(x) != LOW(x)) return false; if (SH(x) != SL(x)) return false; else if (SL(x) == 0) { if (x > 2000000000) x -= 1000000000; // Handle overflow. return isPalindrome(REMAIN(TRIM(x))); } else return isPalindrome(REMAIN(x)); } } };