[Python](PAT)1049 Counting Ones (30 分)

43 篇文章 0 订阅

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 (≤2​30​​).

Output Specification:

For each test case, print the number of 1's in one line.

Sample Input:

12

Sample Output:

5

题目大意

给定一个数字N,求从1-N的数字中,1总共出现了几次

分析

这是一道逻辑题。

使用result存储最后的答案,a存储当前的个、十、百、千……使用left表示左边的字符表示的数字,right表示右边的字符表示的数字。

从各位开始遍历,判断当前位置的字符:

1> 0    则在当前位置可以出现1的次数为left * a次。

2> 1    则在当前位置可以出现1的次数为left * a + right + 1次

3> 其他  则在当前位置出现1 的次数为(left+1)*a

是不是有些玄学?接下来以123为例进行演示。

1>当前处于个位,当前数字为3.只有1、11、21、31……121总共有13个数字的会在这里出现1.而像11、111这样1出现了好几次的数字,因为会在十位、百位的计算中被算进去。所以依然是遵循题意,计算了1的出现次数的。此时result更新为13,a更新为10.

2>当前处于十位,当前数字为2.只有10-19,110-119总共20个数字会在这里出现1.更新result为33,更新a为100.

3>当前处于百位。当前数字为1.只有100-123总共24个数字会在这个地方出现1.因此更新result为57。更新a为1000

4>循环结束,输出57.

python实现

def main():
    n = input()
    result, a = 0,  1
    for x in range(1, len(n) + 1):
        index = len(n) - x
        if n[index] == '0':
            left = n[:index] if n[:index] !='' else 0
            result += int(n[:index]) * a
        elif n[index] == '1':
            left = n[:index] if n[:index] !='' else 0
            right = n[index+1:] if n[index+1:] != '' else 0
            result += int(left)*a + int(right) +1
        else:
            left = n[:index] if n[:index] !='' else 0
            result += (int(left)+1)*a
        a *= 10
    print(result)

if __name__ == "__main__":
    main()

python写PAT甲级,答案全在这了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值