9. Palindrome Number

题目:

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

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

链接:https://leetcode.com/problems/palindrome-number/

一刷

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0 or x and not x % 10:
            return False
        y = x % 10
        z = x / 10
        while z:
            y = 10 * y + z % 10
            z /= 10
        return x == y

用python刷题的缺点是,max int不是ValueError。

判断一半位数的方法:

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0 or x and not x % 10:
            return False
        y = 0
        while x > y:
            y = 10 * y + x % 10
            x /= 10
        return x == y or x == y / 10

整体判断palindrome的题目是否都可以用逆序判断一半的思路?

 

2/6/2017, Java

需要尽可能多的想出来edge case

 1 public class Solution {
 2     public boolean isPalindrome(int x) {
 3         if (x < 0 || x % 10 == 0 && x != 0) return false;
 4         if (x < 10) return true;
 5         int temp = 0;
 6         int digit = 0;
 7         
 8         while (x != temp && x / 10 > temp) {
 9             digit = x % 10;
10             x = x / 10;
11             temp = 10 * temp + digit;
12         }
13         if (x == temp || x / 10 == temp) return true;
14         return false;
15     }
16 }

错误:

1. edge case是分四次才想出来的,应该把所有的思路和想到的edge case都列出来,即使算法改变也有查错的地方

2. 第8行的判断语句,x > temp * 10是错的,x / 10 > temp是对的,相同思路一定要注意准确性。

转载于:https://www.cnblogs.com/panini/p/5555480.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值