实际公里数
解题思路:假设显示的是四位num:
1.千位:num//1000得到整除后的商K;由于每10一轮循环出现1个4;所以在对商K对10取模结果为n,如果余数大于4,那么n需要加1;小于4则n不需要加1;所以千位最后需要减去:n*1000
其他位置的数字也这样判断
2.算出来后需要用num - n*1000 的结果来计算百位上面应该减多少
'''
有一个车的里程表是以整数方式显示的,但是有个毛病,每到4时会直接跳至5,例如3后面本应该显示4,但是直接显示为5。
那么当显示为13公里的时候,实际上是12公里。(因为4被跳了。)
而当显示为15公里的时候,实际上是13公里。(因为4和14被跳了。)
现在请给出一个函数,当输入显示公里数时,返回实际公里数。
'''
'''
'''
def assert_equals(func,target):
if func == target:
print("Success!")
else:
print('Fail! {0} not equals {1}'.format(func, target))
def faulty_odometer(num):
num1 = num
list = []
while num%10>=0 and num !=0:
list.append(num%10)
num = num//10
# 按照从高位到地位的方式千百十个位的顺序存储
list.reverse()
len1 = len(list)-1
for i in list:
temp = 10**len1
k = num1 // temp
n = k // 10
if k % 10 > 4:
n = n + 1
num1 = num1 - n*temp
len1 = len1-1
return num1
assert_equals(faulty_odometer(13),12)
assert_equals(faulty_odometer(15),13)
assert_equals(faulty_odometer(55),40)
assert_equals(faulty_odometer(2005),1462)
assert_equals(faulty_odometer(1500),1053)
assert_equals(faulty_odometer(999999),531440)
assert_equals(faulty_odometer(165826622),69517865)
结果:
Success!
Success!
Success!
Success!
Success!
Success!
Success!
题目来自:
https://fishc.com.cn/forum.php?mod=viewthread&tid=86360&ctid=588