zoukankan      html  css  js  c++  java
  • LeetCode9 Palindrome Number

    题意:

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

    分析:

    自己考虑的方法是利用Reverse Integer,然后查看rev与x是否相等,注意负数和0的判断(这里WA了一次)

    代码1:

     1 class Solution {
     2 private:
     3     int reverse(int x) {
     4         long long result = 0;
     5         while (x != 0) {
     6             int temp = x % 10;
     7             x /= 10;
     8             result = result * 10 +  temp;
     9             if (result > 0x7FFFFFFF || result < -0x7FFFFFFF) {
    10                 return 0;
    11             }
    12         }
    13         return result;
    14     }
    15 public:
    16     bool isPalindrome(int x) {
    17         if (x < 0) {
    18             return false;
    19         }
    20         int rex = reverse(x);
    21         if (rex == 0 && x != 0) { //溢出(不是因为等于0而得到rex = 0)
    22             return false;
    23         }
    24         if (rex == x) {
    25             return true;
    26         }
    27         return false;
    28     }
    29 };

    查看讨论区,有只比较一半的解法,循环中的思路和reverse integer类似,更为简洁,实现如下;

    代码2:

     1 class Solution {
     2 public:
     3     bool isPalindrome(int x) {
     4         if (x < 0 || (x % 10 == 0 && x != 0) ) {
     5             return false;
     6         }
     7         int sum = 0;
     8         while (x > sum) {
     9             int temp = x % 10;
    10             sum = sum * 10 + temp;
    11             x /= 10;
    12         }
    13         if (x == sum || x == sum / 10) {
    14             return true;
    15         }
    16         return false;
    17     }
    18 };
  • 相关阅读:
    centos6.5的开机自动部署出现unsupported hardware detected
    Nginx的安装
    sshpass的使用方法
    dhcp 的安装和配置文件
    SMBus总线概述
    SMBus与I2C的差别
    vim搭建笔记
    pcie dma的玩法
    Virtex6 PCIe 超简版基础概念学习(二)
    揭开Altera公司支持OpenCL的设计工具的神秘面纱
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5735011.html
Copyright © 2011-2022 走看看