LeetCode#67 Add Binary
2015-07-23 20:15
330 查看
Problem Definition:
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
Solution: crack it in a Pythonista way:
Now let's recall something called full adder. And by simulating it, we get another solution, trivial though.
Given two binary strings, return their sum (also a binary string).
For example,
a =
"11"
b =
"1"
Return
"100".
Solution: crack it in a Pythonista way:
def addBinary(a, b): a=int(a,2) b=int(b,2) return bin(a+b)[2:]
Now let's recall something called full adder. And by simulating it, we get another solution, trivial though.
def addBinary(self,a, b): if a==None or a=='': return b if b==None or b=='': return a ia,ib=len(a)-1,len(b)-1 ba,bb,c=[0]*3 s='' while ia>=0 or ib>=0 or c==1: ba=ord(a[ia])-ord('0') if ia>=0 else 0 bb=ord(b[ib])-ord('0') if ib>=0 else 0 ia-=1 ib-=1 r=ba^bb^c #xor c=1 if ba+bb+c>=2 else 0 s+=str(r) return s[::-1]
相关文章推荐
- 内核驱动中常见的miscdevice、platform_device、platform_driver
- 写在开始的话
- dJANGO RESTFRAMEWORK
- 异常处理和I/O流
- android获取外部SDCard(TF Card)
- 黑马程序员——Java多线程之创建线程
- Can not kill oozie job by -kill command
- javascript数组去重的4个方法(转)
- jQuery 源码分析4: jQuery.extend
- 数据结构——N皇后放置方法种数
- 【BASH】自己主动清理rman脚本备份文件
- 【linux】进程存储管理
- django 1.8 官方文档翻译: 2-1-3 元选项 (初稿)
- OC-数组
- hdoj-1213-How Many Tables【并查集】
- 一些mysql语句
- adb logcat不能关闭的问题(进程再启动进程的问题)
- 课程笔记 08:数据结构(清华) 列表-读写接口
- 自定义struts(扩展)--将注解从action上移到service中
- POJ 2896 另解暴力