File tree 4 files changed +88
-1
lines changed
4 files changed +88
-1
lines changed Original file line number Diff line number Diff line change 43
43
* [ Gas Station] ( greedy/gas_station.md )
44
44
* [ Candy] ( greedy/candy.md )
45
45
* [ Word Break ] ( greedy/word_break.md )
46
- * [ Linked List] ( linked_list/README )
46
+ * [ Linked List] ( linked_list/README.md )
47
47
* [ Linked List Cycle] ( linked_list/linked_list_cycle.md )
48
48
* [ Remove Duplicates from Sorted List ] ( linked_list/remove_duplicates_from_sorted_list.md )
49
49
* [ Merge Sorted Lists] ( linked_list/merge_sorted_lists.md )
57
57
* [ Copy List with Random Pointer] ( linked_list/copy_list_with_random_pointer.md )
58
58
* [ Math] ( math/README.md )
59
59
* [ Reverse Integer] ( math/reverse_integer.md )
60
+ * [ String] ( string/README.md )
61
+ * [ Add Binary] ( string/add_binary.md )
60
62
Original file line number Diff line number Diff line change
1
+ # Linked List
Original file line number Diff line number Diff line change
1
+ # String
2
+ > 在这一章,我们将会覆盖leetcode上跟string有关联的题目.
Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments