• [Leetcode] 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.

    题意:判断一个整数是否为回文数。

    思路:常规思路是,将数字转换成字符串或者用数组保存各位上的值,然后从两端开始遍历,判断是否为回文,或者将数反转以后,判断是否相等(这时要注意,若是数很大,怎么办,会溢出)。以上都不行,我就想,数为回文,要高位和低位上的值对应相等,那如何取得各个位上的值了?要是知道这个整数有多少位,就可以取余,或者求商得到对应位的值。按这个思路,我们首先求出的是这个数的位数,我们可以通过不断除10来得到位数。这里值得注意的是:每次比较完以后,如何找到下一对位置上值的比较。代码如下:

     1 class Solution {
     2 public:
     3     bool isPalindrome(int x) 
     4     {
     5         if(x<0) return false;
     6         if(x<10)    return true;
     7 
     8         int base=1;
     9         while(x/base>=10)
    10             base*=10;
    11 
    12         while(x)
    13         {
    14             int lNum=x/base;
    15             int rNum=x%10;
    16             if(lNum !=rNum)
    17                 return false;
    18             
    19             x-=lNum*base;
    20             x/=10;
    21             base/=100;
    22         }    
    23         return true;
    24     }
    25 };
  • 相关阅读:
    python迭代器与iter()函数实例教程
    手动安装python后,交互模式下退格键乱码
    find参数exec、管道符|、xargs的区别
    比较好的网址收集
    sed小知识总结
    irc操作小记
    irssi忽略退出,加入消息
    Web自动化简介
    android&ios区别
    移动自动化应用展望
  • 原文地址:https://www.cnblogs.com/love-yh/p/7112035.html
Copyright © 2020-2023  润新知