注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
技术问题如下。
"""
1. Write a您好! 本帖隐藏的内容需要积分高于 188 才可浏览 您当前积分为 0。 使用VIP即刻解锁阅读权限或查看其他获取积分的方式 游客,您好! 本帖隐藏的内容需要积分高于 188 才可浏览 您当前积分为 0。 VIP即刻解锁阅读权限 或 查看其他获取积分的方式 al">面试小哥很热情,人很好。
我全部拿Python写的代码。代码如下:
- """
- 1. Write a function to add the two binary number strings.
- e.g.
- add('100', '10') -> '110'
- 2. Follow up, add two number strings with specific base
- add('100', '10', 2) -> '110'
- add('100', '9', 10) -> '109'
- 3. Follow up, sum list number strings with specific base
- add_strs(['9', '3', '2'], 10) -> '14'
- """
- def add_str_1(a, b):
- alist = [int(x) for x in a[::-1]]
- blist = [int(x) for x in b[::-1]]
- len_a = len(alist)
- len_b = len(blist)
- carry = 0
- i = 0
- res = []
- while i < len_a or i < len_b or carry != 0:
- tmp = carry
- if i < len_a:
- tmp += alist[i]
- if i < len_b:
- tmp += blist[i]
- if tmp == 3:
- carry = 1
- tmp = 1
- elif tmp == 2:
- carry = 1
- tmp = 0
- else:
- carry = 0
- res.append(tmp)
- i += 1
- return ''.join([str(x) for x in res[::-1]])
- def add_str_2(a, b, base):
- """
- 2. Follow up, add two number strings with specific base
- add('100', '10', 2) -> '110'
- add('100', '9', 10) -> '109'
- """
- alist = [int(x) for x in a[::-1]]
- blist = [int(x) for x in b[::-1]]
- len_a = len(alist)
- len_b = len(blist)
- carry = 0
- i = 0
- res = []
- while i < len_a or i < len_b or carry != 0:
- tmp = carry
- if i < len_a:
- tmp += alist[i]
- if i < len_b:
- tmp += blist[i]
- carry = tmp / base
- tmp = tmp % base
- res.append(tmp)
- i += 1
- return ''.join([str(x) for x in res[::-1]])
- def add_str_3(input_list, base):
- """
- 3. Follow up, sum list number strings with specific base
- add_strs(['9', '3', '2'], 10) -> '14'
- """
- if not input_list:
- return 0
- while len(input_list) >= 2:
- a = input_list.pop()
- b = input_list.pop()
- tmp = add_str_2(a, b, base)
- input_list.append(tmp)
- return input_list[0]
复制代码
Unit Test 测试用例如下:
- import unittest
- from solution import add_str_1
- from solution import add_str_2
- from solution import add_str_3
- class Test(unittest.TestCase):
- def test_add_str_1(self):
- a = '110'
- b = '110'
- res = add_str_1(a, b)
- self.assertEqual('1100', res)
- def test_add_str_2_1(self):
- a = '110'
- b = '110'
- base = 2
- res = add_str_2(a, b, base)
- self.assertEqual('1100', res)
- def test_add_str_2_2(self):
- a = '999'
- b = '1'
- base = 10
- res = add_str_2(a, b, base)
- self.assertEqual('1000', res)
- def test_add_str_2_3(self):
- a = '7'
- b = '2'
- base = 8
- res = add_str_2(a, b, base)
- self.assertEqual('11', res)
- def test_add_str_3_1(self):
- input_list = ['9', '4', '3']
- base = 10
- res = add_str_3(input_list, base)
- self.assertEqual('16', res)
- if __name__ == '__main__':
- unittest.main(verbosity=2)
复制代码
发题攒人品,求过。
|