DAY 9
3
Software Development

## [Day 9] 從LeetCode學演算法 - 0067. Add Binary (Easy)

``````Question:
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contain only characters 1 or 0.
``````
``````Example 1:
Input: a = "11", b = "1"
Output: "100"
``````
``````Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
``````

(不同的語言的int變數所涵蓋的範圍不一定相同)

Python就沒有這種限制，直譯器已經處理好很多事情了，

Java:

``````// Solution from lx223
public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) sum += b.charAt(j--) - '0';
if (i >= 0) sum += a.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
}
``````

Python的部分相對簡單的多(可以偷吃步XD)，

num表示你的字串，base表示這段字串的進位方式

Python:

``````class Solution:
def addBinary(self, a: 'str', b: 'str') -> 'str':
return bin(int(a, 2) + int(b, 2))[2:]
``````

「時間複雜度？」( O(max(len(a), len(b))) )

「Python解是很簡單啦，但可以用一個一個比較的方法嗎？」
(請仿照Java的方式寫給他XD)
(補充: Python的ASCII和數字順序的互轉是 ord(c)跟 chr(a)，

「(Java)j++和++j有什麼不同？」
(++本身是代表將這個值增加1，

0070. Climbing Stairs (Easy)