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
《编程之美》该书中提到过这题的解法
假设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); }
相关文章推荐
- 扩展欧几里德解的数量(51nod 1352)
- (51nod)1009 - 数字1的数量
- 51 nod 最小1的数量 数位DP
- (51Nod - 1107)斜率小于0的连线数量
- 51 nod 1376 最长递增子序列的数量(二维偏序cdq)
- 51-nod 1003 . 阶乘后面0的数量
- [51NOD](1003)阶乘后面0的数量 ---数学
- [51 nod]1009 数字1的数量
- 51 nod 1107 斜率小于0的连线数量
- 51 nod 1003 阶乘后面0的数量
- (51nod)1003 - 阶乘后面0的数量
- 51 nod 1009 数字1的数量
- 3的幂的和 51Nod - 1013(快速幂+等比数列求和+逆元)
- 51 nod 1789 跑的比谁都快
- 51 nod 1010
- 51 nod 1067 Bash游戏 V2
- [51Nod](1284) 2 3 5 7的倍数 ---- 容斥原理
- 数位DP (51nod)
- 两点(51nod 1416)
- 51 nod 1495 中国好区间