Skip to content

Commit 1555ce3

Browse files
committed
add binary
add binary
1 parent b9fa148 commit 1555ce3

File tree

4 files changed

+88
-1
lines changed

4 files changed

+88
-1
lines changed

SUMMARY.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
* [Gas Station](greedy/gas_station.md)
4444
* [Candy](greedy/candy.md)
4545
* [Word Break ](greedy/word_break.md)
46-
* [Linked List](linked_list/README)
46+
* [Linked List](linked_list/README.md)
4747
* [Linked List Cycle](linked_list/linked_list_cycle.md)
4848
* [Remove Duplicates from Sorted List ](linked_list/remove_duplicates_from_sorted_list.md)
4949
* [Merge Sorted Lists](linked_list/merge_sorted_lists.md)
@@ -57,4 +57,6 @@
5757
* [Copy List with Random Pointer](linked_list/copy_list_with_random_pointer.md)
5858
* [Math](math/README.md)
5959
* [Reverse Integer](math/reverse_integer.md)
60+
* [String](string/README.md)
61+
* [Add Binary](string/add_binary.md)
6062

linked_list/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Linked List

string/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# String
2+
> 在这一章,我们将会覆盖leetcode上跟string有关联的题目.

string/add_binary.md

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Add Binary
2+
3+
> Given two binary strings, return their sum (also a binary string).
4+
5+
> For example,
6+
a = "11"
7+
b = "1"
8+
Return "100".
9+
10+
> 题目翻译: 对于给定的两个二进制数字所表达的字符串,我们求其相加所得到的结果, 根据上例便可得到答案.
11+
12+
> 题目分析: 我认为这道题所要注意的地方涵盖以下几个方面:
13+
14+
1. 对字符串的操作.
15+
2. 对于加法,我们应该建立一个进位单位,保存进位数值.
16+
3. 我们还要考虑两个字符串如果不同长度会怎样.
17+
4. int 类型和char类型的相互转换.
18+
19+
> 时间复杂度:其实这就是针对两个字符串加起来跑一遍,O(n) n代表长的那串字符串长度.
20+
21+
代码如下:
22+
23+
```c++
24+
class Solution {
25+
public:
26+
string addBinary(string a, string b) {
27+
int len1 = a.size();
28+
int len2 = b.size();
29+
if(len1 == 0)
30+
return b;
31+
if(len2 == 0)
32+
return a;
33+
34+
string ret;
35+
int carry = 0;
36+
int index1 = len1-1;
37+
int index2 = len2-1;
38+
39+
while(index1 >=0 && index2 >= 0)
40+
{
41+
int num = (a[index1]-'0')+(b[index2]-'0')+carry;
42+
carry = num/2;
43+
num = num%2;
44+
index1--;
45+
index2--;
46+
ret.insert(ret.begin(),num+'0');
47+
}
48+
49+
if(index1 < 0&& index2 < 0)
50+
{
51+
if(carry == 1)
52+
{
53+
ret.insert(ret.begin(),carry+'0');
54+
return ret;
55+
}
56+
}
57+
58+
while(index1 >= 0)
59+
{
60+
int num = (a[index1]-'0')+carry;
61+
carry = num/2;
62+
num = num%2;
63+
index1--;
64+
ret.insert(ret.begin(),num+'0');
65+
}
66+
while(index2 >= 0)
67+
{
68+
int num = (b[index2]-'0')+carry;
69+
carry = num/2;
70+
num = num%2;
71+
index2--;
72+
ret.insert(ret.begin(),num+'0');
73+
}
74+
if(carry == 1)
75+
ret.insert(ret.begin(),carry+'0');
76+
return ret;
77+
}
78+
};
79+
80+
```
81+
82+

0 commit comments

Comments
 (0)