您的位置:首页 > 其它

1的数量(51nod)

2016-12-06 22:59 330 查看
求1-n中出现1的数量。

《编程之美》该书中提到过这题的解法

假设n=abcde,

如果百位上的数字为0,那么,百位上出现1的次数由更高位决定,例如:12013,百位上出现1的情况为,1-199,1100-1199,2100-2199,…,11100~11199,一共有12*100个

如果百位上的数字为1,那么,百位上出现1的次数由高位和低位的数影响,例如:12113,高位1-199,1100-1199,2100-2199,…,11100~11199,一共有12*100个,低位12100~12113,一共113+1个

如果百位上的数字大于1,则百位上可能出现1的次数由更高位决定,例如12213,1-199,1100-1199,2100-2199,…,11100~11199, 12100~12199 共(12+1)*100

#include <cstdio>
int read(){int ret=0;char ch=getchar();while(ch<'0'||ch>'9') ch=getchar();for(;ch>='0'&&ch<='9';ch=getchar()) ret=ret*10+ch-'0';return ret;}
int main()
{
int n=read();
int pos=1,ans=0;
while(n/pos)
{
int low=n-(n/pos)*pos;
int now=(n/pos)%10;
int high=n/(pos*10);
if(now==0)
ans+=high*pos;
else if(now==1)
ans+=high*pos+low+1;
else
ans+=(high+1)*pos;
pos*=10;
}
printf("%d\n",ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: