gpt4 book ai didi

c++ - 采访 : Adding two binary numbers given as strings

转载 作者:行者123 更新时间:2023-11-28 00:46:06 24 4
gpt4 key购买 nike

<分区>

http://www.glassdoor.com/Interview/Facebook-Interview-Questions-E40772.htm 查看一些面试问题时我遇到了以下问题:

Given two string representations of binary numbers (e.g. "1001", "10") write a function that adds them and returns the result as a string as well (e.g. "1011").

这是我开始为这个问题编写的一些 Python 代码(目前还不完整),但我不太确定这是否是最好(甚至正确)的方法。我也考虑过先在 C++ 中实现相同的功能,但考虑到字符串操作中增加的复杂性,我放弃了。

def add_binary(a,b):
temp = ""
carry = false
//i from len(a) to 1 and j from len(b) to 1
bit_sum = add_bit ((a[i],b[j])
if (bit_sum == "10"):
temp.append("0")
carry = true
elif carry:
temp.append(add_bit("1",bit_sum))
else:
temp.append(bit_sum)

return temp.reverse()


def add_bit(b1, b2):
if b1 == '0':
return b2
elif b2 == '0':
return b1
elif (b1 = '1' and b2 =='1'):
return "10"
else return None

a = "1001"
b = "10"
add_binary(a,b)

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com