zoukankan      html  css  js  c++  java
  • 491. Palindrome Number【easy】

    Check a positive number is a palindrome or not.

    A palindrome number is that if you reverse the whole number you will get exactly the same number.

    Notice

    It's guaranteed the input number is a 32-bit integer, but after reversion, the number may exceed the 32-bit integer.

     
    Example

    11, 121, 1, 12321 are palindrome numbers.

    23, 32, 1232 are not palindrome numbers.

    解法一:

     1 class Solution {
     2 public:
     3     /*
     4      * @param num: a positive number
     5      * @return: true if it's a palindrome or false
     6      */
     7     bool isPalindrome(int num) {
     8         //negative number
     9         if(num < 0)
    10             return false;
    11             
    12         int len = 1;
    13         while(num / len >= 10)
    14             len *= 10;
    15             
    16         while(num > 0)    {
    17             
    18             //get the head and tail number
    19             int left = num / len;
    20             int right = num % 10;
    21             
    22             if(left != right)
    23                 return false;
    24             else    {
    25                 //remove the head and tail number
    26                 num = (num % len) / 10;
    27                 len /= 100;
    28             }
    29         }
    30         
    31         return true;
    32     }
    33 };

    分别过滤出头尾2个数进行比较

    解法二:

     1 class Solution {
     2 public:
     3     /*
     4      * @param num: a positive number
     5      * @return: true if it's a palindrome or false
     6      */
     7     bool isPalindrome(int num) {
     8         if (num < 0)  
     9             return false;  
    10               
    11         if (num < 10)  
    12             return true;  
    13               
    14         int digits = 0;  
    15         int t = num;  
    16         int d = 0;  
    17         while(t != 0) t /= 10, ++d;  
    18           
    19         int left = pow(10, d - 1);  
    20         int right = 1;  
    21         while( left >= right)  
    22         {  
    23             if (num / left % 10 != num / right % 10)  
    24                 return false;  
    25               
    26             left /= 10;  
    27             right *= 10;  
    28         }  
    29         return true;  
    30     }
    31 };

    依旧是过滤出头尾2个数进行比较,处理的方式和解法一稍有不同,参考@MagiSu 的代码

  • 相关阅读:
    背景不动,内容滚动的解决方案(移动端)
    移动端真实1px的实现方法
    用户模板和用户场景
    构建之法阅读笔记02
    学习进度六
    NABCD
    构建之法阅读笔记01
    学习进度五
    梦断代码阅读笔记03
    地铁系统
  • 原文地址:https://www.cnblogs.com/abc-begin/p/8204593.html
Copyright © 2011-2022 走看看