Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
这道题的意思是判断输入的数是否是一个回文数字,什么叫回文数字,顺序和逆序得到是同一个值。
我的思路:
1.按照题目意思,先将数值逆序
2.然后将逆序前的值和逆序后的值对比,是否相等,如果相等返回true,否则返回false
关于逆序,有好多办法,
(1)转为字符串调用StringBuilder的reverse()
方法逆序
(2)转为字符串,然后循环字符数组,前后对应位置交换元素得到新的字符数组,转为字符串,再次比较
(3)利用数学的思想来求余,除法计算等来形成新的数值,然后比较
我第一想法是(2),所以实现代码如下所示:
class Solution {
public boolean isPalindrome(int x) {
String num = String.valueOf(x);
char[] ch = num.toCharArray();
int right = ch.length-1;
for(int left=0;left<ch.length/2;left++,right--){
char temp = ch[left];
ch[left] = ch[right];
ch[right] = temp;
}
if(num.equals(new String(ch))){
return true;
}
return false;
}
}
Runtime: 8 ms
Memory Usage: 35.3 MB
思路1的解法:
class Solution {
public boolean isPalindrome(int x) {
StringBuilder sb=new StringBuilder(x+"");
return sb.toString().equals(sb.reverse().toString());
}
}
Runtime: 9 ms
Memory Usage: 36.2 MB
思路3的解法:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
int ans = 0;
int num = x;
while ( num > 0) {
ans = ans * 10 + num % 10;
num = num / 10;
}
if (ans != x) return false;
return true;
}
}
Runtime: 6 ms
Memory Usage: 34.4 MB