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);
        }
    };
  • 相关阅读:
    C语言 assert
    Java6上开发WebService
    unity3d绘制贴图
    unity3d物理引擎
    unity3dVisual Studio Tools for Unity快捷键
    unity3d小案例之角色简单漫游
    unity3d射线(Ray)
    unity3d准备工作
    unity3d编辑器结构
    unity3d碰撞检测
  • 原文地址:https://www.cnblogs.com/double-win/p/3752606.html
Copyright © 2011-2022 走看看