【LeetCode】67. Add Binary 解题报告(Python)
2024-10-19 09:31:27
作者: 负雪明烛
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 日 —— 周六快乐
最新文章
- 两个单选按钮(一个是,一个否 ),一个div层,实现点击隐藏,显示div
- BZOJ 4408 主席数+找规律
- Wix 安装部署教程(七) 获取管理员权限
- C#(winform)为button添加背景图片
- java数据库连接池性能对比
- C# 以管理员方式启动Winform,进而使用管理员控制Windows Service
- FaceBook Twitter实习生简历求内推
- 官网下载Spring dist
- 设计模式(c#)代码总结
- overflow清楚浮动 + 去掉li标签的小圆点
- HDU 4391 Paint The Wall 段树(水
- centos 6.2安装bind 9.8.2 master、slave与自动修改后更新
- [CF697D]Puzzles 树形dp/期望dp
- oracle维护数据的完整性
- iOS下JS与OC互相调用(一)--UIWebView 拦截URL
- 优雅的使用git
- iOS----------YYModel
- Introducation of Servlet filter(servlet过滤器介绍 )
- win7安装Oracle 11g 详细教程
- 快速上手Git