PAT 1049. Counting Ones (30)
来源:互联网 发布:centos ftp没找到 编辑:程序博客网 时间:2024/05/19 14:19
1049. Counting Ones (30)
时间限制
100 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:12Sample Output:
5
先放我的代码。思路是逐位的数1
#include<string>#include<stdio.h>#include<iostream>#include<string.h>#include<queue>#include<algorithm>#include<map>#include<vector>using namespace std;char a[100];int n;int tmp=n;int p=0;long long sum=0;int num(int y) { int ssmm=0; int p=0; int k=1; if(y<0) return 1; while(p<=y) { ssmm+=k*(a[p]-'0'); k*=10; p++; } return ssmm+1; } void compute(int x) { int now=n; int k=1; for(int i=0;i<x;i++) k*=10; for(int i=0;i<x+1;i++) now/=10; sum+=now*k; if(a[x]>'1') sum+=k; else if(a[x]=='1') sum+=num(x-1); } int main(){ cin>>n; tmp=n; while(tmp>0) { int zz=tmp%10; tmp/=10; a[p++]='0'+zz; } for(int i=0;i<p;i++) compute(i); cout<<sum; return 0;}附上别人的。思路一模一样,描述上更清晰。
#include<iostream> using namespace std; int main(){ int N,sum,radix,index; cin >> N; sum = 0; radix = 1; do{ index = N/radix%10; if (index == 0)sum += N / (radix * 10)*radix; /*例如2032 当取到index=0时,此位为1时X1XX ,前面有01两种可能,后面有00~99radix=100种可能, PS:第一次做没有考虑到这种情况,借位有机会为1的情况*/ else if (index==1) sum += N / (radix * 10) *radix+N%radix + 1; /*例如24132,当取到1时,前面00~23种可能的时候,后面可以对应00~99radix=100种可能,而当取到24时,后面只有00~32=33种可能 PS:第一次做没有考虑到这种情况是只是最后一个的可能比较少*/ else if (index > 1)sum += (N / (radix * 10) + 1)*radix; /*例如4542,当取到5时,前面0~4五种可能的时候,后面对应00~99种可能*/ radix *= 10; } while (N / radix!=0); cout << sum<<endl; system("pause"); return 0;}
阅读全文
0 0
- 1049. Counting Ones (30)-PAT
- pat 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- 【PAT】1049. Counting Ones (30)
- PAT.1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones
- PAT 1049. Counting Ones
- PAT--1049. Counting Ones
- PAT Counting Ones (30)
- PAT A 1049. Counting Ones (30)
- 【PAT (Advanced Level)】1049. Counting Ones (30)
- 【PAT甲级】1049. Counting Ones (30)
- 1049. Counting Ones (30) PAT甲级
- PAT甲级.1049. Counting Ones (30)
- PAT甲级练习1049. Counting Ones (30)
- No qualifying bean of type [] is defined
- echarts 浏览器宽度自适应变化、兼容移动设备----实战
- Linux串口应用编程
- Android多渠道打包汇总(一)—— 什么是签名打包
- Python脚本实现树莓派对MPU6050的数据读取
- PAT 1049. Counting Ones (30)
- 深度学习系列教程
- 部分开发工具激活
- Android三种姿势带你玩转360度全景图功能
- codeforces 259-B. Little Elephant and Magic Square(数学)
- 美团编程题
- 明远智睿IMX6Q Android4.4.2移植USBWIFI(RTL8188EUS)
- java中volatile关键字的含义
- 纯js实现简单的汉语转字母