[LeetCode] 67. Add Binary 二进制数相加
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"
解法: 从最低位加到最高位,当前位相加结果是%2,进位是/2,记得处理每一次的进位和最后一次的进位,最后反向输出字符。
Java:
public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() -1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) sum += b.charAt(j--) - '0';
if (i >= 0) sum += a.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
}
Java:
public class AddBinary {
public String addBinary(String a, String b) {
StringBuilder result = new StringBuilder();
int pointerA = a.length()-1;
int pointerB = b.length()-1;
int carry = 0;
while(pointerA>=0 || pointerB>=0){
int sum = carry;
if(pointerA>=0){
sum += (a.charAt(pointerA)-'0');
pointerA--;
}
if(pointerB>=0){
sum += (b.charAt(pointerB)-'0');
pointerB--;
}
result.append(sum%2);
carry = sum/2;
}
if(carry!=0){
result.append('1');
}
return result.reverse().toString();
}
}
Python:
class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
result, carry, val = "", 0, 0
for i in xrange(max(len(a), len(b))):
val = carry
if i < len(a):
val += int(a[-(i + 1)])
if i < len(b):
val += int(b[-(i + 1)])
carry, val = val / 2, val % 2
result += str(val)
if carry:
result += str(carry)
return result[::-1]
Python:
class Solution:
def addBinary(self, a, b):
if len(a)==0: return b
if len(b)==0: return a
if a[-1] == '1' and b[-1] == '1':
return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1')+'0'
if a[-1] == '0' and b[-1] == '0':
return self.addBinary(a[0:-1],b[0:-1])+'0'
else:
return self.addBinary(a[0:-1],b[0:-1])+'1'
Python:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
res = ''
carry = 0
i, j = len(a) - 1, len(b) - 1
while i >= 0 or j >= 0:
su = carry
if i >= 0:
su += int(a[i])
if j >= 0:
su += int(b[j])
carry = su / 2
res += str(su % 2)
i -= 1
j -= 1 if carry > 0:
res += str(carry) return res[::-1]
C++ 1:
class Solution {
public:
string addBinary(string a, string b) {
string res;
size_t res_len = max(a.length(), b.length()) ; size_t carry = 0;
for (int i = 0; i < res_len; ++i) {
const size_t a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0;
const size_t b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0;
size_t sum = carry + a_bit_i + b_bit_i;
carry = sum / 2;
sum %= 2;
res.push_back('0' + sum);
}
if (carry) {
res.push_back('0' + carry);
}
reverse(res.begin(), res.end()); return res;
}
};
C++ 2:
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
int m = a.size() - 1, n = b.size() - 1, carry = 0;
while (m >= 0 || n >= 0) {
int p = m >= 0 ? a[m--] - '0' : 0;
int q = n >= 0 ? b[n--] - '0' : 0;
int sum = p + q + carry;
res = to_string(sum % 2) + res;
carry = sum / 2;
}
return carry == 1 ? "1" + res : res;
}
};
Followup:
如果不是二进制相加,而是十六进制相加呢?只要把算法中的除2和余2换成16,并添加相应的十六进制字母就行了。
如果是带小数的?
All LeetCode Questions List 题目汇总
[LeetCode] 67. Add Binary 二进制数相加的更多相关文章
- [LeetCode] Add Binary 二进制数相加
Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...
- [LintCode] Add Binary 二进制数相加
Given two binary strings, return their sum (also a binary string). Have you met this question in a r ...
- Leetcode 67 Add Binary 大数加法+字符串处理
题意:两个二进制数相加,大数加法的变形 大数加法流程: 1.倒置两个大数,这一步能使所有大数对齐 2.逐位相加,同时进位 3.倒置两个大数的和作为输出 class Solution { public: ...
- LeetCode 67. Add Binary (二进制相加)
Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...
- LeetCode 67 Add Binary(二进制相加)(*)
翻译 给定两个二进制字符串,返回它们的和(也是二进制字符串). 比如, a = "11" b = "1" 返回 "100". 原文 Give ...
- (String) leetcode 67. Add Binary
Given two binary strings, return their sum (also a binary string). The input strings are both non-em ...
- leetCode 67.Add Binary (二进制加法) 解题思路和方法
Given two binary strings, return their sum (also a binary string). For example, a = "11" b ...
- LeetCode 67. Add Binary
Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...
- Java [Leetcode 67]Add Binary
题目描述: Given two binary strings, return their sum (also a binary string). For example,a = "11&qu ...
随机推荐
- 面向切面编程AOP——加锁、cache、logging、trace、同步等这些较通用的操作,如果都写一个类,则每个用到这些功能的类使用多继承非常难看,AOP就是解决这个问题的,python AOP就是装饰器
面向切面编程(AOP)是一种编程思想,与OOP并不矛盾,只是它们的关注点相同.面向对象的目的在于抽象和管理,而面向切面的目的在于解耦和复用. 举两个大家都接触过的AOP的例子: 1)java中myba ...
- 自定义express中间件
const http = require('http') class LikeExpress { constructor() { this.middleList = [] this.routes = ...
- BZOJ 3553: [Shoi2014]三叉神经树 LCT
犯傻了,想到了如果是 0->1 的话就找最深的非 1 编号,是 1 -> 0 的话就找最深的非 0 编号. 但是没有想到这个东西可以直接维护. 假设不考虑叶子节点,那么如果当前点的值是 1 ...
- xamarin/xamarin.forms 在锁屏电源唤醒时保持后台运行
PARTIAL_WAKE_LOCK:保持CPU 运转,屏幕和键盘灯有可能是关闭的. SCREEN_DIM_WAKE_LOCK:保持CPU 运转,允许保持屏幕显示但有可能是灰的,允许关闭键盘灯 SCRE ...
- P2210 Haywire
P2210 Haywire 模拟退火练手题 #include<cmath> #include<ctime> #include<cstdio> #include< ...
- CF1098E Fedya the Potter
CF1098E Fedya the Potter 题意:有一个序列\(A\). 对所有\(1\leq l\leq r\leq |A|\),将\(\gcd_{i=l}^{r}A_i\)加入\(B\)中. ...
- 【JZOJ6225】【20190618】计数
题目 对于一个01串,定义\(f(s)\)为\(f(s) = \sum_{i=0}^{\lfloor \frac{|s|}{2} \rfloor -1 }[s_i=s_{|s|-1-i}]\) 定义\ ...
- 微信小程序电影模板
[外链图片转存失败(img-STw401rR-1565101469846)(https://upload-images.jianshu.io/upload_images/11158618-52efd0 ...
- js中forEach,for in,for of循环的用法详解
一.一般的遍历数组的方法: var array = [1,2,3,4,5,6,7]; for (var i = 0; i < array.length; i) { console.log(i,a ...
- 【POJ1321】棋盘问题
本题传动门 本题知识点:深度优先搜索 + 枚举 + 回溯 题意是要求我们把棋子放在棋盘的'#'上,但不能把两枚棋子放在同一列或者同一行上,问摆好这k枚棋子有多少种情况. 我们可以一行一行地找,当在某一 ...