zoukankan      html  css  js  c++  java
  • 【LeetCode】009. Palindrome Number

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

    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.

    题解:

      easy题

    Solution 1

     1 class Solution {
     2 public:
     3     bool isPalindrome(int x) {
     4         if (x < 0)
     5             return false;
     6         int base = 1;
     7         int tmp = x;
     8         while (tmp > 9) {
     9             tmp /= 10;
    10             base *= 10;
    11         }
    12         
    13         while (x) {
    14             int head = x / base;
    15             int tail = x % 10;
    16             if (head != tail)
    17                 return false;
    18             x = (x % base) / 10;
    19             base /= 100;
    20         }
    21         
    22         return true;
    23     }
    24 };

    Solution 2

     1 class Solution {
     2 public:
     3     bool isPalindrome(int x) {
     4         if (x < 0)
     5             return false;
     6         int base = 1;
     7         while (x / base > 9) {
     8             base *= 10;
     9         }
    10         
    11         while (x) {
    12             int head = x / base;
    13             int tail = x % 10;
    14             if (head != tail)
    15                 return false;
    16             x = (x % base) / 10;
    17             base /= 100;
    18         }
    19         
    20         return true;
    21     }
    22 };
  • 相关阅读:
    Date日期对象
    JAVA适配器
    java 对象的多态性
    简单轮播
    ecshop 教程地址
    瀑布流js排列
    phpcms 搜索结果页面栏目不显示解决 方法
    手机自动跳转
    字串符转换数字、取小数点后两位数的方法
    js 判断鼠标进去方向
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8644360.html
Copyright © 2011-2022 走看看