codewar_Ones and Zeros(二进制与十进制转换)

要求: 将给定的二进制转换为十进制
Input: data = [0, 0, 1, 1]
Output: 3
Clever:
  • 代码片段1
def binary_array_to_number(arr):
	return int("".join(map(str,arr)),2)
	# map(str ,arr) 把数组中的元素全部转化为str类型
  • Some pionts:
    • map()函数

      map() 会根据提供的函数对指定序列做映射。

      map(lambda x,y:x+y,[1,3,5,7,9],[2,4,6,8,10])
      #返回为 新的list
      
    • int(x,[base])

      将x转换为整数。如果x是字符串,则要base指定基数。

    • join连接字符串数组

  • 代码片段2
def binary_array_to_number(arr):
	s = 0
	for digit in arr:
		s = s * 2 + digit
	return s

Let’s say we have some input “so far” such as [a2, a1, a0]. We’ve calculated N2 = a2 * 2^2 + a1 * 2^1 + a0 * 2^0. Now we add another digit (let’s call it b) to the right side of the array. Now we need N3 = a2 * 2^3 + a1 * 2^2 + a0 * 2^1 + b * 2^0. In other words, when we had a2 before, we thought it was the 3rd place, but it turns out it’s the 4th place. a3 before was the 2nd place but it turns out it’s the 3rd. Does that mean we have to recalculate everything with new place values? Well, no. If we look at the relationship between N2 and N3, we see that every “digit” in N2 got multiplied by 2 (and then we added b). In other words N3 = N2 * 2 + b.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值