PAT Advanced Level 1049

来源:互联网 发布:新手学编程怎么开始 编辑:程序博客网 时间:2024/05/22 05:52

题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1049

思路分析:对数的每一位进行分析。每一位出现1的个数由高位数字、低位数字和本位数共同决定

代码如下:

#include<stdio.h>int CountOnes(int n){int count=0;int factor=1;int higher,lower,cur;while(n/factor!= 0){higher=n/(factor*10);lower=n-(n/factor)*factor;cur=(n/factor)%10;switch(cur){case 0:count+=higher*factor;break;case 1:count+=higher*factor+lower+1;break;default:count+=higher*factor+factor;}factor=factor*10;}return count;}int main(){int n;scanf("%d",&n);printf("%d\n",CountOnes(n));return 0;}


0 0