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 };
  • 相关阅读:
    winsows10 小技巧
    数组与智能指针
    卸载 VS2015
    Effective C++
    修改 git commit 的信息
    线程管理
    并发编程简介
    个别算法详解
    git 删除某个中间提交版本
    git 查看某一行代码的修改历史
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8644360.html
Copyright © 2011-2022 走看看