加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:19:27 所属栏目:百科 来源:网络整理
导读:题意: 输入一个正整数N(N=2^30),输出从1到N共有多少个数字包括1。 代码: #define HAVE_STRUCT_TIMESPEC #includebits/stdc++.h using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cinn; int ans=0

题意:

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

代码:

#define HAVE_STRUCT_TIMESPEC
#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin>>n;
int ans=0;
int l=0,r=0,low_bit=1,yushu=0;//当前位左边的数字,当前位右边的数字,当前位,当前位上的数字
while(n/low_bit){
l=n/(10*low_bit);
yushu=n/low_bit%10;
r=n%low_bit;
if(!yushu)
ans+=l*low_bit;//当前位为1时,左边数字可以从0~l-1,故有l*low_bit
else if(yushu==1)
ans+=l*low_bit+r+1;//当前位为1时,有为0时加上右边数字为0~r,故有l*low_bit+r+1
else
ans+=(l+1)*low_bit;//当前位大于1时,左边数字从0~l,当前位只要为1就符合题意,故有(l+1)*low_bit
low_bit*=10;//当前位左移
}
cout<<ans;
return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读