1、题目名称
Palindrome Number(回文数)
2、题目地址
https://leetcode.com/problems/palindrome-number
3、题目内容
英文:Determine whether an integer is a palindrome. Do this without extra space.
中文:确认一个整数是否是回文数
4、解题方法1
将数字翻转后判断与原数字是否相等,可以参考LeetCode第7题(Reverse Integer)的解题思路。Java代码如下:
/**
* 功能说明:LeetCode 9 - Palindrome Number
* 开发人员:Tsybius
* 开发时间:2015年9月24日
*/
public class Solution {
/**
* 判断某数是否为回文数
* @param x 数字
* @return true:是,false:否
*/
public boolean isPalindrome(int x) {
//负数不能为回文数
if (x < 0) {
return false;
}
//反转数字观察是否相等
if (x == reverse(x)) {
return true;
} else {
return false;
}
}
/**
* 反转数字
* @param x 被反转数字
* @return 反转后数字
*/
public int reverse(int x) {
long result = 0;
while (x!=0) {
result = result * 10 + x % 10;
x /= 10;
}
return (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) ? 0 : (int)result;
}
}
5、解题方法2
另一个方法是将数字转换为字符串,再通过StringBuilder类反转字符串,判断两字符串相等。Java代码如下:
/**
* 功能说明:LeetCode 9 - Palindrome Number
* 开发人员:Tsybius
* 开发时间:2015年9月24日
*/
public class Solution {
/**
* 判断某数是否为回文数
* @param x 数字
* @return true:是,false:否
*/
public boolean isPalindrome(int x) {
if (x < 0) return false;
if (x < 10) return true;
String str1 = String.valueOf(x);
String str2 = (new StringBuilder(str1)).reverse().toString();
if (str1.equals(str2)) {
return true;
} else {
return false;
}
}
}
6、解题方法3
还有一个方法,就是直接转换为字符串,然后再分别对字符串对称位置字符进行比较。Java代码如下:
/**
* 功能说明:LeetCode 9 - Palindrome Number
* 开发人员:Tsybius
* 开发时间:2015年9月24日
*/
public class Solution {
/**
* 判断某数是否为回文数
* @param x 数字
* @return true:是,false:否
*/
public boolean isPalindrome(int x) {
if (x < 0) return false;
if (x < 10) return true;
String str = String.valueOf(x);
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - i - 1)) {
return false;
}
}
return true;
}
}
END