UVA 1103 How Many O's?

题目链接:UVA-11038

题意为给定n和m,求n和m之间(包含)的所有数包含的0的个数。

思路是,用cal(x)表示小于等于x的数包含的0的个数。则答案为cal(n)-cal(m-1)。

再把求cal(x)转化为求(sum_i 在第i位为0的小于x的数的个数 )。

要求在第i位为0的数的个数,我们只需要,把x的第i位设为0,然后分别i位左右两侧统计个数即可。

代码如下:

 1 #include"cstdio"
 2 #include"iostream"
 3 #include"cstring"
 4 #include"algorithm"
 5 #include"cstdlib"
 6 #include"vector"
 7 #include"set"
 8 #include"map"
 9 #include"cmath"
10 using namespace std;
11 typedef long long LL;
12 const LL MAXN=10010;
13 
14 LL cal(LL x)
15 {
16     LL ans=1;
17     LL rgt=0;
18     LL ten=1;
19     while(x>=10)
20     {
21         LL p=x%10;
22         x/=10;
23         if(p!=0)
24             ans+=x*ten;
25         else 
26             ans+=(x-1)*ten + (rgt+1);
27         rgt=rgt+ten*p;
28         ten*=10;
29     }
30     return ans;
31 }
32 int main()
33 {
34 #ifdef LOCAL
35     freopen("in.txt","r",stdin);
36     // freopen("out.txt","w",stdout);
37 #endif
38     LL n,m;
39     while(scanf("%lld%lld",&m,&n)==2 && (n!=-1 || m!=-1))
40     {
41         if(m==0) printf("%lld
",cal(n));
42         else printf("%lld
",cal(n)-cal(m-1));
43     }
44     return 0;
45 }
原文地址:https://www.cnblogs.com/zarth/p/6725168.html