• 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)

  • 相关阅读:
    redis模糊查询redis中的key
    通过 saltstack 批量更新 SSL 证书
    大数据处理技术作业——使用HBase&MongoDB&MapReduce进行数据存储和管理
    React常见的一些坑
    Swift学习内容精选(二)
    开户许可证识别 易语言代码
    node 获取请求者的ip地址
    MySQL的binlog日志的简介与查看
    为什么没有办法画圆角?
    mysql
  • 原文地址:https://blog.csdn.net/m0_54689021/article/details/126192699