您的位置:首页 > 其它

【LeetCode】9.Palindrome Number(Easy)解题报告

2017-12-20 21:07 316 查看
【LeetCode】9.Palindrome Number(Easy)解题报告

题目地址:https://leetcode.com/problems/palindrome-number/description/

题目描述:

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

  题意:判断一个数字是否是回文数字。但要注意:1,负数都不是回文数;2,不能通过将数字转为字符串来判断回文,因为使用了额外的空间(即只能使用空间复杂度 O(1) 的方法)(解法一,很意外可以A);3,翻转正数注意整数溢出问题(解法二);4,这个问题有一个比较通用的解法:次提取头尾两个数,判断它们是否相等,判断后去掉头尾两个数(解法三)。

Solutions:

Solution1(虽A但不可取)
class Solution {
public boolean isPalindrome(int x) {
if(x<0){
return false;
}
String temp = Integer.toString(x);
int j=temp.length();
//循环条件中i<(j-1-i)换成i<(j-1)/2就a不了。
for(int i=0 ;i<j&&i<(j-1-i);i++){
if(temp.charAt(i)!=temp.charAt(j-1-i)){
return false;
}
}
return true;
}
}


Solution2(A,但要对溢出进行处理)
class Solution {
public boolean isPalindrome(int x) {
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}

int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
if(revertedNumber>Integer.MAX_VALUE/10||revertedNumber==Integer.MAX_VALUE/10&&x>Integer.MAX_VALUE%10) return false;
x /= 10;
}

// When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
// For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
// since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
return x == revertedNumber || x == revertedNumber/10; //even,odd
}
}


Solution3(本题惯例解法)
class Solution {
public boolean isPalindrome(int x) {
if(x<0) return false;

int temp = 1;
while(x/temp>=10){
temp*=10;
}
while(x > 0){
int left = x/temp;
int right = x%10;
//比较首尾
if(left!=right){
return false;
//x = (x - left*temp)/10;
//if(x<10) return true;
//remove the head and tail number
}else{
x = (x % temp) / 10;
temp /= 100;
}
}
return true;
}
}


Date:2017年12月20日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode