【LeetCode OJ 009】Palindrome Number

題目鏈接:https://leetcode.com/problems/palindrome-number/

題目:

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

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?

示例代碼:

public class Solution 
{
    public boolean isPalindrome(int x)
    {
    	if(x<0)
    		return false;
    	List<Integer> list=new LinkedList<Integer>();
    	int temp;
    	int m=x;
    	//從個位開始取出每一位數,放入LinkedList中
    	while(m>0)
    	{
    		temp=m%10;
    		list.add(temp);
    		m=m/10;
    	}
    	int sum=0;
    	//從LinkedList中依次取出每一位數組成的新數即爲x的逆序數
		for(int i:list)
		{
			sum=sum*10+i;
		}
		//比較是否相等即可判斷
		if(x==sum)
		{
			return true;
		}
		else 
		{
			return false;
		}
    }
}


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