leetcode easy - Add Binary已回收
Question:
Given two binany strings a and b. return their sum as a binary string.
給兩個進位字串a跟b 返回他們的合(也是字串)
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
- 1 <= a.length, b.length <= 104
- a and b consist only of '0' or '1' characters.
- Each string does not contain leading zeros except for the zero itself.
解法 c++
class Solution {
public:
string addBinary(string a, string b){
int n = a.size();
int m = b.size();
int carry = 0;
string result("");
while(n >=0 || m >=0 || carry){
if(n >= 0) carry += a[n--] - '0';
if(m >= 0) carry += b[m--] - '0';
result += (carry%2 + '0');
carry /= 2;
}
reverse(result.begin(), result.end());
return result;
};
}
講解
這題主要是要做二進位字串加法
不過因為長度可能會很長
所以沒辦法轉成數字加起來再轉字串
不過概念上也不難
主要精神就是對齊右邊 算出對應位數的合之後
0+0=> result 0 carry 0
0+1=> result 1 carry 0
1+1=> result 0 carry 1
處理好合的部分放到result
由於result是倒著放進去
所以結束的時候要記得顛倒
大概是這樣
又水一篇
爛兔可以打贏讓我回本嗎
拜託拜託
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.169.181.158 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1649515771.A.C54.html
→
04/09 22:51,
3年前
, 1F
04/09 22:51, 1F
※ 編輯: argorok (1.169.181.158 臺灣), 04/09/2022 22:52:38
→
04/09 22:52,
3年前
, 2F
04/09 22:52, 2F
→
04/09 22:52,
3年前
, 3F
04/09 22:52, 3F
→
04/09 22:53,
3年前
, 4F
04/09 22:53, 4F