[LeetCode] Add Binary

简介: The idea is to add the two binary numbers (represented as strings) from back to forth bit by bit and store the result in the longer string.

The idea is to add the two binary numbers (represented as strings) from back to forth bit by bit and store the result in the longer string. After the shorter string has been added, we continue to handle the carry bit. We may need to append the carry bit to the beginning of the longer string if necessary.

The code is as follows.

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         int m = a.length(), n = b.length(), c = 0, i, j;
 5         if (m < n) return addBinary(b, a);
 6         for (i = m - 1, j = n - 1; j >= 0; i--, j--) {
 7             int ad = a[i] - '0', bd = b[j] - '0';
 8             a[i] = (ad ^ bd ^ c) + '0';
 9             c = (ad + bd + c >= 2);
10         }
11         for (; i >= 0; i--) {
12             int ad = a[i] - '0';
13             a[i] = (ad ^ c) + '0';
14             c = (ad + c >= 2);
15         }
16         if (c) a = '1' + a;
17         return a; 
18     }
19 };

Running the above code on the simple example a = "1", b = "11" will help you get all its details (both the two for loops and the two if statements will be hit) :-)

目录
相关文章
|
6月前
Leetcode Minimum Depth of Binary Tree (面试题推荐)
计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。 我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。
25 0
|
6月前
Leetcode Binary Tree Postorder Traversal(面试题推荐)
非递后续归遍历二叉树,肯定得用到栈。先序遍历很好写,但后续遍历就不是那么容易了。 只需要设置个指针pre,指向最后输出的那个节点就行了,只要判断cur指针指向的是上次输出节点的父节点,且cur无其他未遍历的节点,这个时候就把cur节点输出即可,然后更改pre。原理是要遍历当前节点,其所有子节点都必须遍历完,因为肯定是先左后右,所以只需一个指针保持前一次输出的结果即可。
25 0
|
6月前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
根据LCA的定义,二叉树中最小公共祖先就是两个节点p和q最近的共同祖先节点,LCA的定义没什么好解释的,主要是这道题的解法。
16 0
|
6月前
Leetcode 623. Add One Row to Tree
题目很简单,在树的第d层加一层,值为v。递归增加一层就好了。代码如下
25 0
|
8月前
|
存储 C++ Python
LeetCode刷题---Add Two Numbers(一)
LeetCode刷题---Add Two Numbers(一)
|
11月前
|
存储 算法 安全
LeetCode - #2 Add Two Numbers
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #2 Add Two Numbers
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree