首页 > 代码库 > [leetcode]Add Binary @ Python
[leetcode]Add Binary @ Python
原题地址:https://oj.leetcode.com/problems/add-binary/
题意:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
解题思路:提供两种实现方式吧。
代码一:
class Solution: # @param a, a string # @param b, a string # @return a string def addBinary(self, a, b): aIndex = len(a)-1; bIndex = len(b)-1 flag = 0 s = ‘‘ while aIndex>=0 and bIndex>=0: num = int(a[aIndex])+int(b[bIndex])+flag flag = num/2; num %= 2 s = str(num) + s aIndex -= 1; bIndex -= 1 while aIndex>=0: num = int(a[aIndex])+flag flag = num/2; num %= 2 s = str(num) + s aIndex -= 1 while bIndex>=0: num = int(b[bIndex])+flag flag = num/2; num %= 2 s = str(num) + s bIndex -= 1 if flag == 1: s = ‘1‘ + s return s
代码二:
class Solution: # @param a, a string # @param b, a string # @return a string def addBinary(self, a, b): length = max(len(a),len(b)) + 1 sum = [‘0‘ for i in range(length)] if len(a) <= len(b): a = ‘0‘ * ( len(b) - len(a) ) + a if len(a) > len(b): b = ‘0‘ * ( len(a) - len(b) ) + b flag = 0 i = len(a) - 1 while i >= 0: if int(a[i]) + int(b[i]) + flag == 3: sum[i+1] = ‘1‘ flag = 1 elif int(a[i]) + int(b[i]) + flag == 2: sum[i+1] = ‘0‘ flag = 1 elif int(a[i]) + int(b[i]) + flag == 1: sum[i+1] = ‘1‘ flag = 0 else: sum[i+1] = ‘0‘ flag = 0 i = i - 1 if flag == 1: sum[0] = ‘1‘ if flag == 0: sum = sum[1:length] sum = ‘‘.join(sum) return sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。