不用額外空間判斷一個數是否是迴文形式

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

click to show spoilers.

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.

Solutions:

分別在取最高位和最低位的數字對比一下,不同則返回false。

例如對於 121,取最前面的1用121 / 100,取最末尾的1 用121%10,取完後121變爲2,一次取兩位,max也要一次少兩位(max /= 100)。

易出錯的地方是max循環開始前的值得確定,還有是while循環條件的確定。

有人直接用

                int max=1;
		while(max<=x/10) {
			max*=10;
		}		

就確定了max的值

class Solution {
public:
    bool isPalindrome(int x) {
		if(x<0) {
			return false;
		}
		if(x<10) {
			return true;
		}
		int max=10;
		int t=x/10;
		while(max<t) {			
			max *= 10;
		}
		//max /=10;
		if(x/max >= 10) {
			max *= 10;
		}
		int min=10;
		while(max >= min) {
			if(x/max != x%min){
				return false;
			}
			x %= max;
			x /= min;
			max /= 100;
			//min *= 10;
		}
		return true;
    }
};


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