作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/add-binary/description/

题目描述

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

题目大意

使用字符串表示的二进制数,求他们的和,结果应该也是个字符串。

解题方法

BigInteger类

import java.math.BigInteger;
public class Solution {
public String addBinary(String a, String b) {
BigInteger a_ = new BigInteger(a,2);
BigInteger b_ = new BigInteger(b,2);
return a_.add(b_).toString(2);
}
}

模拟加法

使用的方法简单直接,之前也有类似的题。我先把两个字符串拼接成一样长的,然后再计算,能省去很多判断。如果最后的carry还存在的话,那么需要再加上一个1.

class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
M, N = len(a), len(b)
if M < N:
a = "0" * (N - M) + a
else:
b = "0" * (M - N) + b
stack1 = list(a)
stack2 = list(b)
res = ""
carry = 0
while stack1 and stack2:
s1, s2 = stack1.pop(), stack2.pop()
cursum = int(s1) + int(s2) + carry
if cursum >= 2:
cursum %= 2
carry = 1
else:
carry = 0
res = str(cursum) + res
if carry:
res = "1" + res
return res

日期

2017 年 8 月 17 日
2018 年 11 月 24 日 —— 周六快乐

最新文章

  1. 两个单选按钮(一个是,一个否 ),一个div层,实现点击隐藏,显示div
  2. BZOJ 4408 主席数+找规律
  3. Wix 安装部署教程(七) 获取管理员权限
  4. C#(winform)为button添加背景图片
  5. java数据库连接池性能对比
  6. C# 以管理员方式启动Winform,进而使用管理员控制Windows Service
  7. FaceBook Twitter实习生简历求内推
  8. 官网下载Spring dist
  9. 设计模式(c#)代码总结
  10. overflow清楚浮动 + 去掉li标签的小圆点
  11. HDU 4391 Paint The Wall 段树(水
  12. centos 6.2安装bind 9.8.2 master、slave与自动修改后更新
  13. [CF697D]Puzzles 树形dp/期望dp
  14. oracle维护数据的完整性
  15. iOS下JS与OC互相调用(一)--UIWebView 拦截URL
  16. 优雅的使用git
  17. iOS----------YYModel
  18. Introducation of Servlet filter(servlet过滤器介绍 )
  19. win7安装Oracle 11g 详细教程
  20. 快速上手Git

热门文章

  1. Docker-原理解析
  2. LATEX公式语法
  3. Prometheus_exporter安装与使用
  4. 一起手写吧!ES5和ES6的继承机制!
  5. 转 序列化Serializable和Parcelable的区别详解
  6. 链式栈——Java实现
  7. Linux下强制踢掉登陆用户
  8. 3.6 String 与 切片&amp;str的区别
  9. Spring中的InitializingBean与DisposableBean
  10. 接口测试 python+PyCharm 环境搭建