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是对的,相同思路一定要注意准确性。

  • 相关阅读:
    hbuilder(js+html+css)开发的APP效果实例
    基于ServiceStack.OrmLite框架 代码性能、开发效率皆第一 没有之一
    nodejs+IIS+WebMatrix
    小型设备嵌入式开发(.NET Micro Framework)
    SQL对数据进行统计、常用集合函数
    .Net Micro Framework 嵌入式开发
    js+html+css 开发App
    Dos.ORM
    ORM(ServiceStack,Moon,DbEntry,EasyDb,netnorm )
    商业款ORM servicestack llblgen
  • 原文地址:https://www.cnblogs.com/panini/p/5555480.html
Copyright © 2011-2022 走看看