zoukankan      html  css  js  c++  java
  • LeetCode

    LeetCode - Palindrome Number

    2013.12.1 22:24

    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.

    Solution:

      Basic solution for this problem is to compare the digits at both ends of the number one by one, until all pairs are determined equal.

      Here are the special cases I've come up with:

        1. 0 is of course a palindrome.

        2. INT_MIN and INT_MAX, boundary values can be tricky.

        3. negative numbers like -121?

      Actually the first two case needs special treatment, as they won't work with the code below. The third case cost me 1WA to find out that -121 is not considered a palindrome by LeetCode OJ. For other numbers, the following code segment works just fine.

      Time complexity is O(lg(n)), space complexity is O(1).

    Accepted code:

     1 // 1RE, 1WA, 1AC  must be more careful
     2 class Solution {
     3 public:
     4     bool isPalindrome(int x) {
     5         // 1RE here, ignored the case of INT_MIN
     6         if(x == INT_MAX || x == INT_MIN){
     7             return false;
     8         }
     9         
    10         // IMPORTANT: Please reset any member data you declared, as
    11         // the same Solution instance will be reused for each test case.
    12         int high, low;
    13         
    14         if(x < 0){
    15             // 1WA here, seems negative number is not palindrome, that's unfair..
    16             return false;
    17         }
    18         
    19         if(x == 0){
    20             return true;
    21         }
    22         
    23         high = low = 1;
    24         while(x / high >= 10){
    25             high *= 10;
    26         }
    27         
    28         while(high > low){
    29             if(x / high % 10 != x / low % 10){
    30                 return false;
    31             }else{
    32                 // fixed, didn't cause a WA, lucky..
    33                 high /= 10;
    34                 low *= 10;
    35             }
    36         }
    37         
    38         return true;
    39     }
    40 };
  • 相关阅读:
    年轻人如何去有效的学习(很好的鸡汤,一语惊醒梦中人)
    python基础07 函数
    python基础06 循环
    python基础05 缩进与选择
    python基础04 运算
    python基础03 序列
    python基础02 基本数据类型
    python基础01 Hello World
    CSS3(三)BFC、定位、浮动、7种垂直居中方法
    CSS3(二)Box Model、边距折叠、内联与块标签、CSSReset
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3453093.html
Copyright © 2011-2022 走看看