|
The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12. Input Specification:Each input file contains one test case which gives the positive N (≤230). Output Specification:For each test case, print the number of 1's in one line. |
Sample Input:
12
Sample Output:
5
题目大意
求1~N出现了几个1
1~11算出现4个1,即 1,10,11
思路
数学题,可以直接推算出每个位数1出现多少次
C/C++
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main()
{
LL N,op=1,result=0;
cin >> N;
while (N>=op){
LL key = N/op%10;
LL left = N/(op*10);
LL right = N%op;
if(key==0) result += left*op;
else if(key==1) result += left*op+right+1;
else result += (left+1)*op;
op*=10;
}
cout << result << endl;
return 0;
}
该博客介绍了一种算法,用于计算从1到给定正整数N之间所有数字中1的总数。通过数学推算,分别计算每个位上1出现的次数,最后给出C/C++代码实现。
314

被折叠的 条评论
为什么被折叠?



