[LeetCode] 67. Add Binary 二进制数相加

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

For example,
a = "11"
b = "1"
Return "100".

思路:

从最低位加到最高位,当前位相加结果是%2,进位是/2,记得处理每一次的进位和最后一次的进位,最后反向输出字符。

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();
    }
}

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;
    }
};

  

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]

if __name__ == ‘__main__‘:
    result = Solution().addBinary(‘11‘, ‘1‘)
    print result

  

后续Followup:

如果不是二进制相加,而是十六进制相加呢?只要把算法中的除2和余2换成16,并添加相应的十六进制字母就行了。

如果是带小数的

原文地址:https://www.cnblogs.com/lightwindy/p/8481729.html

时间: 2024-10-25 06:14:54

[LeetCode] 67. Add Binary 二进制数相加的相关文章

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

[LintCode] Add Binary 二进制数相加

Given two binary strings, return their sum (also a binary string). Have you met this question in a real interview? Yes Example a = 11 b = 1 Return 100 LeetCode上的原题,请参见我之前的博客Add Binary. class Solution { public: /** * @param a a number * @param b a num

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(二进制相加)(*)

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

Add Binary 二进制数相加

Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 二进制数想加,并且保存在string中,要注意的是如何将string和int之间互相转换,并且每位相加时,会有进位的可能,会影响之后相加的结果.而且两个输入string的长度也可能会不同.这时我们需要新建一个string,它的长度是两

leetCode 67.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) { int len = Math.max(a.len

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] 67. Add Binary 解题报告

Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 判断数字时用charAt(i)-'0'即可 public String addBinary(String a, String b) { StringBuilder sb = new StringBuilder(); int i=a.l

leetcode 67. Add Binary (高精度加法)

Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 简单的二进制高精度加法. class Solution { public: string addBinary(string a, string b) { string ans=""; int c=0,i=a.len