【JAVA、C++】LeetCode 009 Palindrome Number

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

解题思路一:

双指针法,逐位判断

Java代码如下:

	static public boolean isPalindrome(int x) {
		if (x < 0)
			return false;
		int temp = x,beginIndex = 0, endIndex = 0;
		while (temp >= 10) {
			temp /= 10;
			endIndex++;
		}
		while (beginIndex < endIndex) {
			if ((int)((x / Math.pow(10,beginIndex))%10) != (int)((x / Math.pow(10,endIndex))%10))
				return false;
			beginIndex++;
			endIndex--;
		}
		return true;
	}

 解题思路二:

计算出回文的值,然后判断回文的值是否等于自身:

C++:

 1 #include<algorithm>
 2 using namespace std;
 3 class Solution {
 4 public:
 5     bool isPalindrome(int x) {
 6         if (x < 0)
 7             return false;
 8         long longx = x, palindromex = 0;
 9         while (x) {
10             palindromex = palindromex * 10 + x % 10;
11             x /= 10;
12         }
13         return longx == palindromex;
14     }
15 };

 

posted @ 2015-04-26 10:13  TonyLuis  阅读(192)  评论(0编辑  收藏  举报