[LintCode] Add Binary 二进制数相加

简介:

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

Example

a = 11

b = 1

Return 100

LeetCode上的原题,请参见我之前的博客Add Binary

class Solution {
public:
    /**
     * @param a a number
     * @param b a number
     * @return the result
     */
    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;
    }
};

本文转自博客园Grandyang的博客,原文链接:二进制数相加[LintCode] Add Binary ,如需转载请自行联系原博主。

相关文章
base -2 Number——进制转换
题目描述 Given an integer N, find the base −2 representation of N. Here, S is the base −2 representation of N when the following are all satisfied: S is a string consisting of 0 and 1. Unless S= 0, the initial character of S is 1. Let S=SkSk−1…S0, then S0×(−2)0+S1×(−2)1+…+Sk×(−2)k=N.
86 0
|
存储 Java Python
LeetCode 2:两数相加 Add Two Numbers
​给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
667 0
|
Java C++ 索引
# Leetcode 67:Add Binary(二进制求和)
Leetcode 67:Add Binary(二进制求和) (python、java) 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. 给定两个二进制字符串,返回他们的和(用二进制表示)。
1350 0