zoukankan      html  css  js  c++  java
  • [LeetCode]68. 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.

    Subscribe to see which companies asked this question

    解法1:首先想到的就是将整数转换为字符串,然后从两头往中间对比即可。或者将每一位分别取出来后暂存再前后比较。但是这样都需要额外的空间。

    class Solution {
    public:
        bool isPalindrome(int x) {
            if (x < 0) return false;
            string s = to_string(x);
            int i = 0, j = s.size() - 1;
            while (i < j)
                if (s[i++] != s[j--]) return false;
            return true;
        }
    };

    解法2:可以想办法每次都取出整数的最高位和最低位进行比较,然后去掉这个最高位和最低位,取新的整数的最低位和最高位比较……

    class Solution {
    public:
        bool isPalindrome(int x) {
            if (x < 0) return false;
            int num = x, n = 0;
            while (num > 0) {
                ++n;
                num /= 10;
            }
            if (n == 1) return true;
            int i = 1, j = n - 1;
            while (i <= j) {
                int low = x % (int)pow(10, i) / (int)pow(10, i - 1);
                int high = x / (int)pow(10, j) % 10;
                if (low != high) return false;
                ++i;
                --j;
            }
            return true;
        }
    };

    一种更简单的写法,严格按照上述思路:

    class Solution {
    public:
        bool isPalindrome(int x) {
            if (x < 0) return false;
            int n = 1;
            while (x / n >= 10) n *= 10;
            while (x > 0) {
                int low = x % 10;
                int high = x / n;
                if (low != high) return false;
                x = (x % n) / 10; //取出中间剩余的数字
                n /= 100; //注意每次去掉两位,因此除数相应缩小100倍
            }
            return true;
        }
    };
  • 相关阅读:
    三极管8050和8550对管的参数
    三极管9014 管脚
    水深不语,人稳不言
    编译结果分析
    三母运算符
    C语言关键词解释
    51定时器初值的计算
    聪明人都在远离手机虚假繁荣的“人脉”关系
    每段路,都是一种领悟
    你的灯亮着吗读后感二
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4949712.html
Copyright © 2011-2022 走看看