题目描述
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
解题思路
本题看了一下这个大佬的思路,在这里再梳理一下,附上参考链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/。
该方法依次计算个位,十位,百位到最高位的1出现的次数。
1. 比如计算十位,这里以n = 204为例,cur表示当前位为0,hight表示高位,这里为2,digit表示进制,十位则digit为10, 所以十位为1的数就为10~119,这里可以直接数出来,为[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 110, 111, 112, 113,114,115,116,117,118,119],总共有20个数,可以直接通过high * digit计算得出,其他的数也一样。
2. 还是计算十位,这里如果n=214,当前位cur = 1,高位high = 2,低位low = 4, digit还是为10, 所以十位为1的数为10~214,数出来就是[10,11,12,13,14,15,16,17,18,19,110,111,112,113,114,115,116,117,118,119,210,211,212,213,214],总共25个数字,那么可以推算为high * digit + low + 1
3. 同理,如果n = 254,当前位cur = 5, 高位high = 2, 低位low = 4, digit为10, 十位为1的数为10~219,数出来就是[10,11,12,13,14,15,16,17,18,19,110,111,112,113,114,115,116,117,118,119,210,211,212,213,214,215,216,217,218,219],总共30个数字,可以推算为(high + 1) * digit
所以从个位开始进行遍历,初始时digit为1。
class Solution: def NumberOf1Between1AndN_Solution(self, n): digit, res = 1, 0 high, cur, low = n // 10, n % 10, 0 while high != 0 or cur != 0: if cur == 0: res += high * digit elif cur == 1: res += high * digit + low + 1 else: res += (high + 1) * digit low += cur * digit cur = high % 10 high //= 10 digit *= 10 return res S = Solution() print(S.NumberOf1Between1AndN_Solution(5))