题解 | #挑7#
挑7
https://www.nowcoder.com/practice/ba241b85371c409ea01ac0aa1a8d957b
这题是专门出给执拗狂的题:如果python3 的话其实很简单,用遍历就可以挑出来,条件是
for k in range(1,int(input())):
if '7' in str(k) or k%7==0
count += 1
但是当我写完以后发现用时只超过了20%python用户以后,我就知道有执拗狂使用了自己推导了数学公式的做法:
所以我也试着推了一下:基本思路是,先算整除7的数总和(count1),再算包含7的所有数字的总和(count2),最后计算又包含7又能被7整除的数的总和(count3)
最终结果=count1+count2-count3
比较绕,大家看看就好:
while True:
try:
num=int(input())
try:
num=int(input())
#count1比较好算,直接除以7就行
count1 = num // 7
bit = len(str(num))
count1 = num // 7
bit = len(str(num))
#count2稍微绕一些,基本思路是,先算个位包含7的数总和,再算十位包含7的数总和(这时候要排除个位上有7的情况),然后是百位(排除个位十位上有7),以此类推直到计算出所有包含7的数的和
count2 = 0
for i in range(bit):
pro= 0
s='0'
for j in range(bit - i, bit):
s = s+str(num)[j]
for k in range(int(s)+1):
if not '7' in str(k):
pro += 1
count2 = 0
for i in range(bit):
pro= 0
s='0'
for j in range(bit - i, bit):
s = s+str(num)[j]
for k in range(int(s)+1):
if not '7' in str(k):
pro += 1
#一个比较难处理的地方是,计算某一位上有7,这一位后面的数有多少个,要分类讨论,这里不做赘述
if int(str(num)[bit - i - 1]) > 7:
count2 += (num // (10 ** (i + 1)) + 1) * (9**i)
elif int(str(num)[bit - i - 1]) == 7:
count2 += (num // (10 ** (i + 1)) ) * (9 ** i) + pro
else:
count2 += max(0,(num // (10 ** (i + 1)))) * (9**i)
if int(str(num)[bit - i - 1]) > 7:
count2 += (num // (10 ** (i + 1)) + 1) * (9**i)
elif int(str(num)[bit - i - 1]) == 7:
count2 += (num // (10 ** (i + 1)) ) * (9 ** i) + pro
else:
count2 += max(0,(num // (10 ** (i + 1)))) * (9**i)
#count3没法用公式算,只能遍历,但是不用每个数都遍历,只要计算7的倍数即可
count3 = 0
c = 7
while c <= num:
if '7' in str(c):
count3 += 1
c += 7
print(count1 + count2 - count3)
except:
break
count3 = 0
c = 7
while c <= num:
if '7' in str(c):
count3 += 1
c += 7
print(count1 + count2 - count3)
except:
break