简便算法计算一个数乘以11的结果:Multiply_by_11

在计算一个数乘以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的错误结果。

实际就是对字符串的操作,并不难,只是需要考虑的情况比较多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值