声明: 仅个人小记
暴力法
#include <iostream>
#include <ctime>
using namespace std;
int main(
void)
{
clock_t startTime, endTime;
int n, x;
cin >> n >> x;
startTime = clock();
int t;
int cnt =
0;
for (
int i =
1; i <= n; i ++) {
t = i;
while (t) {
if (t%
10 == x) cnt ++;
t /=
10;
}
}
endTime = clock();
cout << cnt << endl;
cout <<
"time elpased: " <<
double(endTime-startTime) *
1000 /CLOCKS_PER_SEC <<
"ms" << endl;
cout << endTime-startTime << endl;
return 0;
}
优化
#include <iostream>
#include <ctime>
using namespace std;
int main(
void)
{
int n, x;
cin >> n >> x;
int startTime, endTime;
startTime = clock();
int t;
int cnt =
0;
int k =
1;
int a;
int b = n;
while (b) {
a = b %
10;
b = b /
10;
cnt += b * k;
if (a > x) cnt += k;
else if (a == x) cnt += (n%k+
1);
k *=
10;
}
if (x ==
0) {
cnt --;
int p =
10;
int q =
0;
while (n/
10) {
q += p;
p *=
10;
n/=
1;
}
cnt -= q;
}
endTime = clock();
cout << cnt << endl;
cout <<
"time elpased : " << (
double)(startTime-endTime)*
1000/CLOCKS_PER_SEC <<
"ms"<<endl;
return 0;
}
时间花费对比
0;