在计算一个数乘以11时我们有简便算法:
There is a simple trick to multiplying any two-digit number by 11 in your head:
Add the two digits together
Place the sum between the two digits!
Note if the total goes over, carry the sum on to the next digit
比如:
23 * 11
Add together 2 and 3 to make 5
Place 5 between the two digits to make 253
77 * 11
Add together 7 and 7 to make 14
Place 4 between the two digits to make 747
Carry the 1 to make 847
用python写这种简便算法:
def multiply_by_11(num):
rst = num[-1]
ten = [None]*len(num)
ten[-1] = 0
for i in range(len(num)-1):
sm = int(num[-(i+1)])+int(num[-(i+2)])
if sm+ten[-(i+1)] < 10:
## 如果加起来没有超过10,取第一位,sm后的系数为0
ten[-(i+2)] = 0
rst = str(int(str(sm)[0])+ten[-(i+1)])+rst
if sm+ten[-(i+1)] == 10:
##这种情况很特殊,要单独拿出来说,比如4个连续的数是4596,45这个位置很尴尬。
ten[-(i+2)] = 1
rst = str(0)+rst
if sm+ten[-(i+1)] > 10:
## 如果加起来超过10了,要取第二位,sm后的系数为1
ten[-(i+2)] = 1
rst = str(int(str(sm)[1])+ten[-(i+1)])+rst
if len(num)<3:
final_rst = str(int(num[0])+ten[-(len(num))])+rst
else:
final_rst = str(int(num[0])+ten[-(len(num)-1)])+rst
return final_rst
结果:
multiply_by_11('12345678987654321')
#'135802468864197531'
# 如果不考虑:if sm+ten[-(i+1)] == 10:这一行的情况,这个结果会是错的
multiply_by_11('85')
# 935
# 如果没有考虑到if len(num)<3: 这一行的情况,可能会得到835的错误结果。
实际就是对字符串的操作,并不难,只是需要考虑的情况比较多。