Project Euler Problem 36

版权声明:代码属于原创,转载请联系作者并注明出处。 https://blog.csdn.net/weixin_43379056/article/details/83414053

Problem 36 : Double-base palindromes

The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)

#include <iostream>
#include <ctime>
#include <cassert>

using namespace std;

class PE0036
{
private:
    static const int max_number = 1000000; // one million
    static const int max_digits = 32;

    int m_digits[max_digits];    
    int getDigits(int number, int base);

public:
    bool checkDoubleBasePalindromes(int number);
    int  getSumOfDoubleBasePalindromes();
};

int PE0036::getDigits(int number, int base)
{
    int numOfDigits = 0; 

    while(number> 0)
    {
        m_digits[numOfDigits++] = number%base;
        number /= base; 
    }

    return numOfDigits;
}

bool PE0036::checkDoubleBasePalindromes(int number)
{
    int numOfBase10Digits = getDigits(number, 10);
    for(int i=0; i<numOfBase10Digits/2; i++)
    {
        if(m_digits[i] != m_digits[numOfBase10Digits-1-i])
        {
            return false;
        }
    }

    int numOfBase2Digits = getDigits(number, 2);
    for(int i=0; i<numOfBase2Digits/2; i++)
    {
        if(m_digits[i] != m_digits[numOfBase2Digits-1-i])
        {
            return false;
        }
    }

    return true;
}

int PE0036::getSumOfDoubleBasePalindromes()
{
    int sum = 0;

    for(int number=1;number<max_number;number++)
    {
        if (true == checkDoubleBasePalindromes(number))
        {
#ifdef UNIT_TEST
            cout << number << " is palindromic in both bases" << endl;
#endif
            sum += number;
        }
    }
    return sum;
}

int main()
{
    clock_t start = clock(); 

    PE0036 pe0032;

    assert(true == pe0032.checkDoubleBasePalindromes(585));

    cout << "The sum of all numbers, less than one million, which are palindromic ";
    cout << "in base 10 and base 2 is "<<pe0032.getSumOfDoubleBasePalindromes()<<endl;

    clock_t finish = clock();
    double duration = (double)(finish - start) / CLOCKS_PER_SEC;
    cout << "C/C++ running time: " << duration << " seconds" << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43379056/article/details/83414053