二进制加法

# -*- coding: utf-8 -*-

# 在 list 前补 0
def complement_short_num(num, length):
  for i in range(length):
    num.insert(0, 0)
  return num

def add_binary_number(num1, num2):
  length1 = len(num1)
  length2 = len(num2)
  min_length = length1 if length1 < length2 else length2
  max_length = length1 if length1 > length2 else length2
  different_length = max_length - min_length

  if length1 < length2:
    num1 = complement_short_num(num1, different_length)
  else:
    num2 = complement_short_num(num2, different_length)

  # 初始化结果数组
  num3 = complement_short_num([], max_length + 1)

  carry = 0  # 进位
  for i in range(1, max_length + 1):
    sum = num1[-i] + num2[-i] + carry  # 得益于 python 特性从 list 尾部开始计算
    if sum > 1:
      num3[-i] = sum % 2
      carry = 1
    else:
      num3[-i] = sum
      carry = 0

  # 为结果加进位
  if carry == 1:
    num3[0] = 1

  return num3   

sum = add_binary_number([1, 1, 0], [1, 1, 1, 1, 1])
print(sum)
2016-04-14 19:0183