打印数字回文

产生N个数字回文

1,2,..,9,11,22,..,99,101,....


The order of the palindrome is only related to the "left half" to the number
E.g:
for two digit palindrome, the "left half" are 1,2,3,4,..,9 which makes 11,22,33,44,...99
Under the situation of calculating two digits palindrome, when the "left half" reaches "10"
then, we have stepped into three digits palindrome calculation. it begins at 10, then 11, 12.
....19 which make 101,111,121,...,191
And so on....


int MakePalindrom(int nNum, bool bOddDigits);

void PrintNPalindrom(int n)
{
        assert(n > 0);

        bool bOddDigits = true;
        int e = 1;
        int nDigitStart = 1;
        int nDigitLimit = 10;

        cout<<MakePalindrom(e, bOddDigits)<<endl;

        for (int i = 1; i < n; i++)
        {
                e++;

                if (e == nDigitLimit)
                {
                        bOddDigits = !bOddDigits;
                        if (bOddDigits)
                        {
                                nDigitLimit *= 10;
                                nDigitStart *= 10;
                                e = nDigitStart;
                        }
                        else
                                e = nDigitStart;
                }

                cout<<MakePalindrom(e, bOddDigits)<<endl;
        }
}

int MakePalindrom(int nNum, bool bOddDigits)
{
        assert(nNum > 0);

        vector<int> vec;
        int nTmp = nNum;
        while (0 != nTmp)
        {
                vec.push_back(nTmp % 10);
                nTmp /= 10;
        }

        vector<int>::iterator it = vec.begin();
        if (bOddDigits)
                it++;

        for (; it != vec.end(); it++)
                nNum = nNum*10 + *it;

        return nNum;
}


你可能感兴趣的:(打印数字回文)