码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • PAT甲级:1049 Counting Ones


    题目描述:

    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
    

    代码长度限制

    16 KB

    时间限制

    400 ms

    内存限制

    64 MB

    题目大意: 

    给出一个n,求从0到n一共出现几个1

    解题思路: 

    这题还是有点复杂的,看了一下别人的代码,基本思路是一位一位考虑,也就是计算这一位为1的数有几个,用now表示当前位的值,left为左边的数字,right为右边的数字,a为当前位的位数,以3105为例:

    • 当now>=2时,比如分为310 5 0,此时now=5也就是说可以取(0~310)1,这些数当前位为1,res+=(left+1)*a
    • 当now==1时,比如3 1 05,此时1后面的数不能取全到a,只能取到right,所以res+=left*a+right+1
    • 当now==0时,比如31 0 5,此时只能当(0~30)时当前位才能取1,所以res+=left*a

    Python3代码: 

    1. n = int(input())
    2. left,right,now,a = 0,0,0,1
    3. res = 0
    4. while n // a :
    5. left = n // (a*10)
    6. right = n % a
    7. now = n // a % 10
    8. if now == 0 : res += left * a
    9. elif now == 1 : res += left * a + 1 + right
    10. else : res += (left+1) * a
    11. a *= 10
    12. print(res)

  • 相关阅读:
    VUE+Spring Boot前后端分离开发实战(二):基于VUE+elementUI实现登录页面
    QT数据库,实现数据库增删改查
    新渠道+1!TDengine Cloud 入驻 Azure Marketplace
    文本表示(Representation)
    机器学习集成学习进阶Xgboost算法原理
    接口测试vs功能测试
    第七章 查找
    第七章用Python实现对Excel文件中的数据进行md5加密
    YGG GAP 第一季 NFT 背后的设计理念
    React中Props的使用
  • 原文地址:https://blog.csdn.net/m0_54689021/article/details/126192699
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号