zoukankan      html  css  js  c++  java
  • 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是对的,相同思路一定要注意准确性。

  • 相关阅读:
    Dede 自定义频道解析
    没有什么想说的,但既然来了,也就留下一句
    Title和META标签参数详解,SEO优化中的title和META标签的重要性
    Jsoup HTML 解析器 用法介绍
    php 相关方面内容、
    Html.ActionLink Url.Action的用法
    Asp.Net MVC2.0 Url 路由入门实例篇
    asp.net mvc 在View中获取Url参数的值
    SSH2实现数据库和界面的分页
    struts2中的ModelDriven使用
  • 原文地址:https://www.cnblogs.com/panini/p/5555480.html
Copyright © 2011-2022 走看看