1-n里有多少个1
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int n=10;
cin >> n;
int f[10];
int x[10];
f[0] = 0;
f[1] = 1;
x[0] = 0;
x[1] = 1;
for (int i = 2; i < 10; i++) {
x[i] = x[i - 1] * 10;
f[i] = f[i - 1] * 10 + x[i];
}
int y = n;
int s = 0;
int k = 0;
int len = 0;
int rd[10];
while (y != 0) {
rd[len++] = y % 10;
y /= 10;
}
for (int i = len - 1; i >= 0; i--) {
if (rd[i] == 0) {
continue;
}
if (rd[i] == 1) {
s += n%x[i+1] + 1;
}
else {
s += x[i+1];
}
s += (rd[i]) * f[i];
}
cout << s << endl;
}
1-n里有多少包含1的数
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int n=10;
cin >> n;
int f[10];
int x[10];
f[0] = 0;
f[1] = 1;
x[0] = 0;
x[1] = 1;
for (int i = 2; i < 10; i++) {
x[i] = x[i - 1] * 10;
f[i] = f[i - 1] * 9 + x[i];
}
int y = n;
int s = 0;
int k = 0;
int len = 0;
int rd[10];
while (y != 0) {
rd[len++] = y % 10;
y /= 10;
}
for (int i = len - 1; i >= 0; i--) {
if (rd[i] == 0) {
continue;
}
if (rd[i] == 1) {
s += n%x[i+1] + 1;
s += f[i];
break;
}
else {
s += x[i+1];
s += (rd[i]-1) * f[i];
}
}
cout << s << endl;
}