zoukankan      html  css  js  c++  java
  • [LeetCode] Palindrome Number

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

    click to show spoilers.

    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.

    每次判断第一位和最后一位是否相等,如果相等,去掉第一位和最后一位数,继续比较直到结束。注意中间可能会出现0的情况。

    class Solution {
    public:
        bool isPalindrome(int x) {
            if(x<0)
                return false;
            int x0,xlen;//x的首位和最后一位数
            int xCopy = x;
            int weight = 1;
            while(xCopy>=10){
               xCopy /= 10;
               weight *= 10;
            }
    
            xCopy = x;
            while(xCopy>=10){
               x0  = xCopy % 10;
               xlen = xCopy /weight;
               if(x0 == xlen){//如果相等,去掉开始和结尾的数字
                   xCopy -= (x0+xlen*weight);
                   xCopy /= 10;
                   weight /= 100;
                   if(xCopy==0)
                       return true;
                   else if(xCopy<weight){//防止中间有0的情况
                       int weightNew = 1;
                       int xCopy0 = xCopy;
                       while(xCopy0>=10){
                          xCopy0 /= 10;
                          weightNew *= 10;
                       }
                       int NumZero = 1;
                       int weightNew1 = weightNew*10;
                       while(weightNew1 != weight){//开头有几个0
                           weightNew1 *= 10;
                           NumZero++;
                       }
    
                       while(NumZero){//末尾几个若不是0,则返回false
                           if(xCopy % 10 != 0)
                               return false;
                           else{
                               xCopy /= 10;
                               weight /= 100;
                               NumZero--;
                           }
                       }
                   }
               }else
                   return false;
            }//end while
            return true;
        }//end func
    };
  • 相关阅读:
    用SQL SERVER取分组数据第一条:查出每个班级的成绩第一名
    [转]spring beans.xml
    [转]为什么要使用框架
    MySQL 5.6 for Windows 解压缩版配置安装
    [转]hql 语法与详细解释
    [转]slf4j + log4j原理实现及源码分析
    [转]最详细的Log4j使用教程
    yii2 checkbox 的使用实例
    Magento Order 状态详解
    yii2 设置多个入口文件
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3928327.html
Copyright © 2011-2022 走看看