荣誉版主
- 积分
- -2403
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2010-5-4
- 最后登录
- 1970-1-1
|
Generate n palindrome natural numbers.
like 1,2,..,9,11,22,..,99,101,....
wwwyhx 发表于 2011-7-15 16:01 ![]()
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;
- }
复制代码 |
|