【PAT甲级】1049 Counting Ones (30 分)(类似数位DP思想的模拟)

题意:

输入一个正整数N(N<=2^30),输出从1到N共有多少个数字包括1。

AAAAAccepted code:

 1 #define HAVE_STRUCT_TIMESPEC
 2 #include<bits/stdc++.h>
 3 using namespace std;
 4 int main(){
 5     ios::sync_with_stdio(false);
 6     cin.tie(NULL);
 7     cout.tie(NULL);
 8     int n;
 9     cin>>n;
10     int ans=0;
11     int l=0,r=0,low_bit=1,yushu=0;
12     while(n/low_bit){
13         l=n/(10*low_bit);
14         yushu=n/low_bit%10;
15         r=n%low_bit;
16         if(!yushu)
17             ans+=l*low_bit;
18         else if(yushu==1)
19             ans+=l*low_bit+r+1;
20         else
21             ans+=(l+1)*low_bit;
22         low_bit*=10;
23     }
24     cout<<ans;
25     return 0;
26 }

 

 

 

posted @ 2019-10-02 08:19  sewage  阅读(188)  评论(0编辑  收藏  举报