zoukankan      html  css  js  c++  java
  • LeetCode题解(9)--Palindrome Number

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

    思想: 先计算出这个整数的逆序数,然后比较它和原来的数每位是否都相同即可。另外要注意负数没有回文数,还应该考虑overflow一定不是回文数。

    AC代码:

     1 class Solution {
     2 public:
     3     bool isPalindrome(int x) {
     4         if(x<0)
     5             return false;
     6         int y=0,tmp=x;
     7         while(tmp!=0){
     8             y=10*y+tmp%10;
     9             tmp=tmp/10;
    10         }
    11         while(x!=0 || y!=0){
    12             if(x%10!=y%10)
    13                 return false;
    14             x=x/10;
    15             y=y/10;
    16         }
    17         return true;
    18     }
    19 };

    advance:

    其实可以不求出逆序数,直接比较,见讨论板的代码:

     1 class Solution {
     2 public:
     3     bool isPalindrome(long long x) {
     4         if (x < 0) return false;
     5         long long d = 10, e = 10;
     6         while (x / d) d *= 10;
     7         while (d > e)
     8         {
     9             if ((x % d) / (d / 10) != (x % e) / (e / 10))
    10                 return false;
    11             d /= 10;
    12             e *= 10;
    13         }
    14         return true;
    15     }
    16 };
  • 相关阅读:
    C#操作Redis Set 无序集合
    C#操作Redis Hash数据表
    C#操作Redis List 列表
    C#操作Redis String字符串
    Redis 小结
    建造者模式
    外观模式
    模板方法模式
    原型模式
    select ie6 的bug 层级
  • 原文地址:https://www.cnblogs.com/aezero/p/4490722.html
Copyright © 2011-2022 走看看