LeetCode[String]: Add Binary

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

For example,

a = "11"

b = "1"

Return "100".

我的C++实现代码如下:

string addBinary(string a, string b) {
    string sum;
    int carry = 0;
    for (int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; --i, --j) {
        string bitAdd("0");
        int src1 = (i >= 0 ? a[i] - '0' : 0);
        int src2 = (j >= 0 ? b[j] - '0' : 0);
        bitAdd[0] +=  (src1 + src2 + carry) & 1;
        carry = ((src1 + src2 + carry) & 2) ? 1 : 0;
        sum = bitAdd + sum;
    }

    if (carry) {
        string s("1");
        sum = s + sum;
    }

    return sum;
}
时间: 2024-10-25 14:52:13

LeetCode[String]: Add Binary的相关文章

【LeetCode】Add Binary

Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". public class Solution { public String addBinary(String a, String b) { if(a.equalsIgnoreCase("")||a==null) r

Leetcode 数 Add Binary

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Add Binary Total Accepted: 9509 Total Submissions: 37699 Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". 题意:

[LeetCode][JavaScript]Add Binary

https://leetcode.com/problems/add-binary/ Add Binary Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 长整型二进制加法. 1 /** 2 * @param {string} a 3 * @param {string} b 4 *

leetCode 67. Add Binary 字符串

67. Add Binary Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 思路: 1.将两个字符串按数组相加得到新数组. 2.将新数组转换成结果. 代码如下: class Solution { public:     string addBinary(string a, str

LeetCode 67. Add Binary (二进制相加)

Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 题目标签:Math 题目给了我们两个string a 和 b,让我们把这两个二进制 相加. 首先把两个string 的长度得到,然后从右向左 取 两个string 的 digit. 增设一个 carry = 0: 每一轮把 digit

LeetCode 67. Add Binary

Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 这个题目只要注意各种情况你就成功了一大半,特别要注意的是对进位赋值后可能产生的变化,以及最后一位进位为1时, 我们要把这个1插进来.同时注意字符串的低位是我们数值的高位 class Solution { public: string

[leetcode] 16. Add Binary

这个题目相对有点奇怪,题目如下: Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". 可能是我思路的问题吧,我之前是在考虑先将string转成int或者double,然后将二进制转为十进制进行计算,最后再将这个十进制转为二进制再转为string返回.这个思路本来是没问题的.但是.

LeetCode 67 Add Binary(二进制相加)(*)

翻译 给定两个二进制字符串,返回它们的和(也是二进制字符串). 比如, a = "11" b = "1" 返回 "100". 原文 Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". 分析 我一開始写了这个算法,尽管实现

leetCode(52):Add Binary

Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". 题目并不复杂,以下是我的程序,后面是别人的程序,瞬间low了好大一截! 冗长!!!!!!! class Solution { public: string addBinary(string a, string b) { stri