給兩個binary string,給出相加之後的結果string。
- 因為數字由低位往高位相加,所以 i = n - 1, j = m - 1開始。
- 因為兩個數字長度可能不一樣。所以每次必須判斷是否大於等於0
int na = i >= 0 ? a[i--] - '0' : 0;
int nb = j >= 0 ? b[j--] - '0' : 0;
- 結果往字串前面疊加,因為越後面越是MSB。
- 最後還有一個carrier
string addBinary(string a, string b) {
auto n = a.length();
auto m = b.length();
int i = n - 1, j = m - 1;
int sum{0}, carrier{0};
string rtn;
while(i >= 0 || j >= 0) {
int na = i >= 0 ? a[i--] - '0' : 0;
int nb = j >= 0 ? b[j--] - '0' : 0;
sum = na + nb + carrier;
carrier = sum / 2;
sum %= 2;
rtn = (char)(sum + '0') + rtn;
}
if(carrier) rtn = '1' + rtn;
return rtn;
}
leetcode
刷題
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Syncing