zoukankan      html  css  js  c++  java
  • [LeetCode 题解]: palindromes

    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.

    题解: 

    求解回文数(提示,回文数是指一个数A,将其翻转之后的到数B,且有A=B, 例如: 1,11 , 131, 65356 等)

    (1) 回文数是自然数,最小的回文数为0

    (2) 不能使用额外存储空间, 因此不能采用字符串翻转来做。

    (3) 不能直接将整个数翻转过来,可能出现“溢出”。

    受到条件(3)的启发, 既然不能整个翻转,能否部分翻转呢? 尝试之后发现有如下结论:

    将数A分成左右相等的部分(高位部分A1,低位部分A2):

    特别的: 如果A的长度为奇数,那么处于中间数位的数字对于回文比较不会产生影响。因此可以忽略。

    将A2 翻转,得到A2‘ ,那么有

    若A1 = A2’ , A为回文数

    否则A不是回文数。

    class Solution {
    public:
        bool isPalindrome(int x) {
            int temp=x,n=0,len=0,i;
            if(x<0) return false;
    
            while(temp>0)    //计算数字长度
            {
                temp/=10; len++;
            }
    
            for(i=0;i<len/2;i++)   //二分, 高位保留,低位翻转相乘 
            {
                n = n*10 + x%10;
                x/=10;
            }
            if(len%2) x/=10;   // 如果是奇数位,中间数字可以忽略
            return (n==x);
        }
    };
  • 相关阅读:
    设计模式-工厂设计模式
    Spring Batch BATCH_JOB_SEQ 出现死锁问题
    windows 安装 jenkins 自动化构建部署至linux服务器上
    Git安装
    MAVEN(一) 安装和环境变量配置
    Jenkins 安装
    jenkins操作
    linux firewalld 防火墙操作命令
    【Azure Redis 缓存】Azure Redis读写比较慢/卡的问题排查
    【Azure 服务总线】向服务总线发送消息时,返回错误代码Error code : 50009
  • 原文地址:https://www.cnblogs.com/double-win/p/3752606.html
Copyright © 2011-2022 走看看