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.

    程序代码:

    #include <gtest/gtest.h>
    
    using namespace std;
    
    bool isPalindrome2(int x)
    {
        bool bResult = false;
        if (x < 0)
        {
            return false;
        }
    
        int tempData[20] = {0};
        int tempIdx = 0;
        int tempX = x;
        long long rValue = 0;
        while (tempX)
        {
            tempData[tempIdx++] = tempX % 10;
            tempX /= 10;
        }
    
        for (int i=0; i<tempIdx;++i)
        {
            rValue = rValue*10 +tempData[i];
        }
    
        return (x == rValue);
    }
    
    bool isPalindrome3(int x)
    {
        if (x < 0)
            return false;
    
        long long nValue = 0;
        int temp = x;
        while (temp)
        {
            nValue = nValue*10 + temp % 10;
            temp /= 10;
        }
    
        return (x == nValue);
    }
    
    bool isPalindrome(int x)
    {
        if (x < 0)
            return false;
    
        int dev = 1;
        while (x / dev >= 10)
        {
            dev *= 10;
        }
    
        while (x != 0)
        {
            int l = x / dev;
            int r = x % 10;
            if (l != r)
                return false;
    
            x = (x % dev) / 10;
            dev /= 100;
        }
    
        return true;
    }
    
    TEST(Pratices, tIsPalindrome)
    {
        // 123 false
        // 121 true
        // -111 false
        // 0 true
        // 2147483647 false
        ASSERT_FALSE(isPalindrome(123));
        ASSERT_TRUE(isPalindrome(121));
        ASSERT_FALSE(isPalindrome(-111));
        ASSERT_TRUE(isPalindrome(0));
        ASSERT_FALSE(isPalindrome(2147483647));
    
    
    }

    参考相关:

    http://articles.leetcode.com/palindrome-number

  • 相关阅读:
    正则表达式的贪婪匹配(.*)和非贪婪匹配(.*?)
    jQuery + css 公告从左往右滚动
    C# process 使用方法
    存储过程与SQL的结合使用
    img标签的方方面面
    kibana 5.0.0-alpha5 安装
    es5.0 v5.0.0-alpha 编译安装
    奇怪的hosts文件
    阿里云 api 的文档拼写错误
    centos 7 systemd docker http proxy
  • 原文地址:https://www.cnblogs.com/Quincy/p/5299279.html
Copyright © 2011-2022 走看看