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

【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日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值