You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
987 B
35 lines
987 B
/*
|
|
问题描述:
|
|
输入一个整数n,求1~n这n个整数的十进制表示中1出现的次数
|
|
例如,1~13中包含1的数字有1、10、11、12、13因此其出现6次
|
|
*/
|
|
|
|
#include <iostream>
|
|
using namespace std;
|
|
// 函数用于计算从1到n中'1'出现的次数
|
|
int countDigitOne(int n){
|
|
int count = 0;
|
|
long long factor = 1;// 用来表示当前分析的位(个位、十位、百位等)
|
|
while(n / factor > 0){
|
|
long long lower= n - (n / factor) * factor;// 当前位以下的数字
|
|
long long current=(n / factor) % 10;
|
|
long long higher=n / (factor * 10);
|
|
if(current == 0){
|
|
count += higher * factor;
|
|
}
|
|
else if(current == 1){
|
|
count += higher * factor + lower + 1;
|
|
}
|
|
else {
|
|
count +=(higher + 1) * factor;
|
|
}
|
|
factor *= 10;// 进入到下一位
|
|
}
|
|
return count;
|
|
}
|
|
int main(){
|
|
int n;
|
|
cin >> n;
|
|
cout<< countDigitOne(n)<<endl;
|
|
return 0;
|
|
}
|