1. 程式人生 > >leetcode第9題——*Palindrome Number

leetcode第9題——*Palindrome Number

題目

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?

思路

題目要求不可以使用額外的儲存空間,一般來說需要利用遞迴實現。注意提示:負數不是迴文數,如果將整型數轉換為字串,注意這用到了額外的儲存空間,如果試著翻轉一個整型數,則會遇到翻轉後可能溢位的問題。筆者使用判斷高位和低位是否相等的方法,只需要定義一個計數變數即可實現,沒有佔用額外的儲存空間。另外儘量使用for迴圈代替while迴圈,因為執行時間相對短一些。

程式碼

Python

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if (x < 0) | (x == 0x7FFFFFFF):
            return False
        i = 1
        temp = x/10
        while(temp > 0):
            temp /= 10
            i += 1
        #知道數有多少位後,迴圈判斷最高位是否等於最低位
        for i in range(i-1,0,-2):
            base = pow(10,i)
            if(x/base == x%10):
                x = (x%base)/10
                continue
            else:
                return False
        return True

Java

public class Solution {
    public boolean isPalindrome(int x) {
        int i,base;
		if(x < 0 || x == 0x7FFFFFFF) return false;
        //先看看數有多少位;
		for(i = 1;x/(int)Math.pow(10, i) > 0;i++);
		
		for(i--;i>0;i -= 2){
		    base = (int)Math.pow(10, i);
			if(x/base == x%10){
				//最高位跟最高位相等,則去掉最高位和最低位並進行下次迴圈;
				x = (x%base)/10;
				continue;
			}
			else return false;
		}
		return true;
    }
}