- 为了依次求个位,十位,百位中1的个数,我们可以把这个数字分为三部分,高位数字,当前位数字,低位数字。
- 如果当前位为0,那么此位为1的数目与高位数字有关
- 如果当前位为1,那么此位为1的数目与高位和地位都有关
- 如果当前位其他,那么此位为1的数目与高位数字有关
- 具体规律看源代码
#include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
int factor = 1;
int count = 0;
while (N / factor != 0) {
int highNum = N / (factor * 10);
int curNum = (N / factor) % 10 ;
int lowNum = N - (N / factor) * factor;
switch(curNum) {
case 0:
count += highNum * factor;
break;
case 1:
count += highNum * factor + lowNum + 1;
break;
default:
count += (highNum + 1) * factor;
}
factor *= 10;
}
cout << count << endl;
return 0;
}