[LeetCode] Palindrome Number

要是面試遇到這道題,估計要掛了,想了很久才做出來。

因爲不許使用多餘的空間,所以一開始想的是兩頭縮小,比如12321->232->3,最後認爲對稱。結果遇到1021就失敗了,02變成2,也認爲兩邊對稱。後來就想多了,覺得有什麼特殊的算法,最後又回到這個想法,中間開始縮小。

雖然代碼有點Ugly,很長,很容易出錯,但值得欣慰的是完全按照要求來的,呵呵一下吧。

class Solution {
public:
    bool isPalindrome(int x) {
		if (x < 0) {
			return false;
		}

		if (x >= 1000000000) {
			if (x / 100000 % 10 == x % 100000 / 10000) {
				x = x % 10000 + x / 100000 * 10000;
				return isPalindrome(x);
			}
			else {
				return false;
			}
		}
		else if (x >= 100000000) {
			x = x % 10000 + x / 100000 * 10000;
			return isPalindrome(x);
		}
		else if (x >= 10000000) {
			if (x / 10000 % 10 == x % 10000 / 1000) {
				x = x % 1000 + x / 100000 * 1000;
				return isPalindrome(x);
			}
			else {
				return false;
			}
		}
		else if (x >= 1000000) {
			x = x % 1000 + x / 10000 * 1000;
			return isPalindrome(x);
		}
		else if (x >= 100000) {
			if (x / 1000 % 10 == x % 1000 / 100) {
				x = x % 100 + x / 10000 * 100;
				return isPalindrome(x);
			}
			else {
				return false;
			}
		}
		else if (x >= 10000) {
			x = x % 100 + x / 1000 * 100;
			return isPalindrome(x);
		}
		else if (x >= 1000) {
			if (x / 100 % 10 == x % 100 / 10) {
				x = x % 10 + x / 1000 * 10;
				return isPalindrome(x);
			}
			else {
				return false;
			}
		}
		else if (x >= 100) {
			x = x % 10 + x / 100 * 10;
			return isPalindrome(x);
		}
		else if (x >= 10) {
			if (x / 10 == x % 10) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return true;
		}
    }
};


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