zoukankan      html  css  js  c++  java
  • 9. Palindrome Number

    问题描述:

    Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

    Example 1:

    Input: 121
    Output: true
    

    Example 2:

    Input: -121
    Output: false
    Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
    

    Example 3:

    Input: 10
    Output: false
    Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

    解题思路:

    看到Palindrome就首先想到回文的性质也即定义:关于中心对称。

    若数字由奇数个数字组成,则关于中心数字对称; 若数字由偶数个数字组成,则关于中间的(虚拟的)轴对称。

    想到几种特殊情况:

      1. x = 0 时,x为回文

      2. x < 0 时,x一定不为回文

    首先想到的方法是:将x的最低位取出放到新的数字y里,但是这样有一个风险:x反过来的数字y可能会出现溢出。

    这时我们应该利用回文的性质,不需要全部反过来,只反一半:

      若x由偶数个数字组成,那么x与y相等则为回文

      若x由奇数个数字组成,根据我们的判定条件:y去掉最后一位与x相等则为回文

    代码:

    class Solution {
    public:
        bool isPalindrome(int x) {
            if(x == 0){
                return true;
            }
            if(x % 10 == 0){
                return false;
            }
            int y = 0;
            //get the last digit of x and put it into y
            while(x > y){
                y = y*10 + x % 10;
                x /= 10; 
            }
            //check in even digits or odd digits.
            return (x == y) || (x == y/10);
        }
    };
  • 相关阅读:
    XP系统无法安装net framework 4.0 解决方法
    StructureMap DI & IoC 工具介绍
    Castle ActiveRecord学习实践(7)级联
    Error.popStackFrame 函数
    抽象泄漏(leaky abstraction)
    [Exception]IIS6:The entry "*" has already been added的解决方法
    ASP.NET 设计模式 读书摘记2
    PHP模块开发(一) PHP环境搭建
    PHP函数HTTP 相关函数
    PHP函数FTP文件传输函数
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/11263303.html
Copyright © 2011-2022 走看看