o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
用python回答下面的问题:给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。 示例 1: 输入:n = 13 输出:6 示例 2: 输入:n = 0…
- User
用python回答下面的问题:给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。 示例 1: 输入:n = 13 输出:6 示例 2: 输入:n = 0 输出:0 提示: 0 <= n <= 109
- Assistant
下面是一个Python函数,用于计算小于等于给定整数 n 的非负整数中数字1出现的次数:
pythondef countDigitOne(n: int) -> int: if n <= 0: return 0 total_count = 0 digit_position = 0 # Position of the digit (starting from 0 for units place) while n // (10 ** digit_position) > 0: power = 10 ** digit_position next_power = power * 10 current = (n // power) % 10 left = n // next_power right = n % power if current == 0: total_count += left * power elif current == 1: total_count += left * power + right + 1 else: total_count += (left + 1) * power digit_position += 1 return total_count # 示例 print(countDigitOne(13)) # 输出:6 print(countDigitOne(0)) # 输出:0这个函数的工作原理是遍历数字的每一位,根据当前位的数字以及高位和低位的信息,累加出现数字1的次数。算法的时间复杂度是 O(log n),适合处理 n 高达 10^9 的情况。