PAT(甲级)1049
2015-09-26 10:19
302 查看
1049. Counting Ones (30)
时间限制10 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.
Input Specification:
Each input file contains one test case which gives the positive N (<=230).
Output Specification:
For each test case, print the number of 1's in one line.
Sample Input:
12
Sample Output:
5
#include <cstdio> #include <cstring> #include <cstdlib> int Counting1(char *p); int Count1ToN(int &n){ if(n<=0) return 0; char p[50]; sprintf(p,"%d",n); int count=Counting1(p); return count; } int Pow10(int n){ int base=10; int res=1; while(n){ if(n&0x1) res *=base; base *=base; n >>=1; } return res; } int Counting1(char *p){ if(!p||*p<'0'||*p>'9') return 0; int first = *p-'0'; int length =strlen(p); if(length==1){ if(first >=1) return 1; else return 0; }else{ int part1=0; if(first >1) part1=Pow10(length-1); else if(first ==1) part1=atoi(p+1)+1; int part2=first*(length-1)*Pow10(length-2); int remain=Counting1(p+1); return part1+part2+remain; } } int main() { int N; scanf("%d",&N); int count = Count1ToN(N); printf("%d\n",count); return 0; }
相关文章推荐
- leetcode 080 Remove Duplicates from Sorted Array II(难易度:Medium)
- Bios工程师手边事—battery
- 自定义的RPC的Java实现
- JAVA-文件压缩
- 大道至简读后感
- MVC学习笔记---各种上下文context
- WPF 中图标路径问题
- jqery实现10X10的表格,双击消失
- WPF 中图标路径问题
- PAT(甲级)1048
- C语言复习day2
- uvalive 4671 - K-neighbor substrings 快速傅利叶变换
- PAT(甲级)1047
- 快速开发一个PHP扩展
- 机房收费系统开发进度月报
- 安卓Button控件OnClickListener的三种实现方式
- Filter实现登录功能限制
- html与css笔记
- 基本算法研究1-冒泡排序算法测试
- jQuery全选功能