leetcode 67 Add Binary

Add Binary
Total Accepted: 46815
Total Submissions: 189215 My Submissions

                     

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 result = "";
        int c = 0;
        int i = a.size() - 1;
        int j = b.size() - 1;

        while(i >= 0 || j >=0 ||c ==1)
        {
            c += i >= 0 ? a[i--] - '0':0;
            c += j >= 0 ? b[j--] - '0':0;
            result = char( c% 2 + '0') + result;
            c /= 2;

        }

        return result;

    }
};

c语言解决方案:

char* addBinary(char* a, char* b) {
    int n, m;
    for (n=0; *a; a++, n++) ;
    for (m=0; *b; b++, m++) ;
    char *p = (char*)malloc(m>n ? m+2 : n+2), *last = p;
    int c = 0;
    while (n || m || c) {
        int s = c;
        if (n) {
            s += *(--a)-'0';
            --n;
        }
        if (m) {
            s += *(--b)-'0';
            --m;
        }
        *last++ = (s&1)+'0';
        c = s>>1;
    }
    *last=0;
    char *start = p, t;
    while (start+1 < last) { // reverse string
        t = *start;
        *start++=*(--last);
        *last=t;
    }
    return p;
}

数字电路版本代码:加法器的实现
https://leetcode.com/discuss/40846/c-4ms-solution-inspired-by-hardware-full-adder-circuit

python 的三个版本:

class Solution:
    # @param {string} a
    # @param {string} b
    # @return {string}
    def addBinary(self, a, b):
        i, m, n, result, carry = 1, len(a), len(b), [], 0
        while i <= m or i <= n:
            temp = carry
            if i <= m:
                temp += int(a[-i])
            if i <= n:
                temp += int(b[-i])

            carry = temp / 2
            result.append(str(temp % 2))
            i += 1

        if carry:
            result.append(str(carry))

        return ''.join(result[::-1])

or a really short one if you want

class Solution:
    # @param {string} a
    # @param {string} b
    # @return {string}
    def addBinary(self, a, b):
        return '{0:b}'.format(int(a, 2) + int(b, 2))

class Solution:
    # @param {string} a
    # @param {string} b
    # @return {string}
    def addBinary(self, a, b):
        return bin(int(a,2) + int(b,2))[2:]



时间: 2024-10-02 07:20:27

leetcode 67 Add Binary的相关文章

leetcode 002 add two numbers C语言

问题描述 leetcode 002 add two numbers C语言 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *l, *p; l = (struct ListNode*)malloc(sizeof(struct ListNode)); l->val = l1->val + l2->val; p = l; l1 = l1->next; l

[LeetCode]95.Unique Binary Search Trees II

[题目] Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 confused what "

[LeetCode]*106.Construct Binary Tree from Inorder and Postorder Traversal

题目 Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 思路 思路和[LeetCode]*105.Construct Binary Tree from Preorder and Inorder Traversal一样. 代码 /*---------------------

[LeetCode] Trim a Binary Search Tree 修剪一棵二叉搜索树

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary

[LeetCode]*105.Construct Binary Tree from Preorder and Inorder Traversal

题目 Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 思路 主要是根据前序遍历和中序遍历的特点解决这个题目. 1.确定树的根节点.树根是当前树中所有元素在前序遍历中最先出现的元素. 2.求解树的子树.找出根节点在中序遍历中的位置,根左边的所有元素就是左子树,根右边的所有元

LeetCode 258 Add Digits(数字相加,数字根)

翻译 给定一个非负整型数字,重复相加其所有的数字直到最后的结果只有一位数. 例如: 给定sum = 38,这个过程就像是:3 + 8 = 11,1 + 1 = 2,因为2只有一位数,所以返回它. 紧接着: 你可以不用循环或递归在O(1)时间内完成它吗? 原文 Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given

[LeetCode]114.Flatten Binary Tree to Linked List

[题目] Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 [分析] 在先序遍历的过程中把二叉树转为链表. 用pre记住当前节点的前一节点.节点的右指针作为链表指针,同时左指针赋空(第一次wrong就是因为没赋空). pre->ri

[LeetCode]96.Unique Binary Search Trees

[题目] Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 [分析] 如果把上例的顺序改一下,就可以看出规律了. 比如,以 1 为根的树的个数

[LeetCode]99.Recover Binary Search Tree

[题目] Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? [解析] O(n) 空间的解法是,开一个指针数组