从低位开始:
耗时:4031 CLOCKS_PER_SEC (未输出)
#include <vector>
#include <algorithm>
#include <iostream>
#include<ctime>
using namespace std;
void GenerateCandidate(int n, vector<int>& Candidate, vector<int>& Filter)
{
int base = 1;
for (int i=1; i<n; ++i)
{
base *= 10;
}
int baseUp = base*10;
int remainder = base % n;
if (remainder != 0)
{
int quotient = base / n;
base = (quotient+1)*n;
}
int number = base;
do
{
int numberTest = number/10;
if(binary_search(Filter.begin(), Filter.end(), numberTest))
{
Candidate.push_back(number);
}
number += n;
} while(number < baseUp);
}
void InitFilter(vector<int>& Filter)
{
for (int i=1; i<10; ++i)
{
Filter.push_back(i);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> candidate;
vector<int> filter;
InitFilter(filter);
//candidate.reserve(100000000);
//filter.reserve(100000000);
for (int i=2; i<9; ++i)
{
GenerateCandidate(i, candidate, filter);
//copy(candidate.begin(), candidate.end(), ostream_iterator<int>(cout, "\n"));
filter.clear();
candidate.swap(filter);
}
candidate.swap(filter);
//copy(candidate.begin(), candidate.end(), ostream_iterator<int>(cout, " "));
cout<<endl <<"count:" <<candidate.size();
cout<<endl <<"time:"<<clock();
char c;
cin>>c;
return 0;
}
从高位开始:
耗时:0秒(未输出)
#include <iostream>
#include<ctime>
using namespace std;
int count =0;
void FindNumber(int base, int power, int end)
{
int bounce = base+9;
int remainder = base%power;
if (0 != remainder)
{
remainder = power - remainder;
}
base += remainder;
do
{
if (power == end)
{
//cout << base <<" ";
count++;
}
else if(base != 0)
{
FindNumber(base*10, power+1, end);
}
base += power;
} while(base<=bounce);
}
void FindNumber(int end)
{
FindNumber(0, 1, end);
}
int _tmain(int argc, _TCHAR* argv[])
{
FindNumber(9);
cout<<endl<<count;
cout<<endl <<"time:"<<clock();
char c;
cin>>c;
return 0;
}