当前位置:网站首页>PAT Class A: 1049 Counting Ones
PAT Class A: 1049 Counting Ones
2022-08-06 19:02:00 【Blackening KS】
Title description:
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:
5Code length limit
16 KB
Time limit
400 ms
Memory Limit
64MB
Subject to the effect:
Given an n, find how many 1s appear from 0 to n
Things to solve the problem:
This question is still a bit complicated. I looked at other people's code. The basic idea is to consider each bit, that is, to calculate how many numbers this bit is 1, and use now to represent the value of the current bit, and left isThe number on the left, right is the number on the right, and a is the number of digits in the current digit, taking 3105 as an example:
- When now>=2, for example, it is divided into 310 5 0. At this time, now=5 means that (0~310)1 can be taken. The current bit of these numbers is 1, res+=(left+1)*a
- When now==1, such as 3 1 05, the number after 1 cannot be taken to a, but only to the right, so res+=left*a+right+1
- When now==0, such as 31 0 5, the current bit can only take 1 when (0~30), so res+=left*a
Python3 code:
n = int(input())left,right,now,a = 0,0,0,1res = 0while n // a :left = n // (a*10)right = n % anow = n // a % 10if now == 0 : res += left * aelif now == 1 : res += left * a + 1 + rightelse : res += (left+1) * aa *= 10print(res)边栏推荐
猜你喜欢

Euro-NCAP-2023-Safe Driving Assistance Driver Condition Monitoring DMS and Speed Limit Assist Test Procedure-Chinese Version

最全的交换机知识汇总,看完这一篇就全明白了

SMW0 SAP上传模板

Nacos Source Code Analysis Topic (4) - Service Discovery

go install 指定版本包

Euro-NCAP-HWA test procedure Chinese version

小熊派学习—无线联网开发

tensorflow-gpu 2.6.0版本安装教程

Quick Start to CarSim Simulation (17) - ADAS Range and Tracking Sensors

Nacos source code analysis topic (3) - service heartbeat
随机推荐
搭建 EwoMail 邮件服务器
go install 指定版本包
ubuntu忘记mysql密码,怎么办
深度学习之基础知识
农村孩子高压线。。。
61:第五章:开发admin管理服务:14:开发【友情链接列表查询,接口】;(核心是:理解MongoDB,查询数据的逻辑)
PettingZoo:多智能体游戏环境库入门
CarSim Simulation Advanced Advanced (3) ---VS Command Line (3)
DNS外带注入
PreScan quickstart to master speak of 20 actuators (traffic participants)
星起航:跨境电商试综区为广大卖家提供更多的市场发展机遇
Build EwoMail mail server
好消息|又一省22年二建成绩查询时间公布
Nacos Source Code Analysis Topic (4) - Service Discovery
Open3D 机载点云电力线提取
最全的交换机知识汇总,看完这一篇就全明白了
codesys TCP客户端程序
SSL 证书生成
小熊派学习—网络应用开发
How from form to get default value