--- title: 'LeetCode 67. Add Binary' disqus: hackmd --- # LeetCode 67. Add Binary ## Description Given two binary strings a and b, return their sum as a binary string. ## Example Input: a = "11", b = "1" Output: "100" Input: a = "1010", b = "1011" Output: "10101" ## Constraints 1 <= a.length, b.length <= 10^4^ a and b consist only of '0' or '1' characters. Each string does not contain leading zeros except for the zero itself. ## Answer 此題可先抓出最大長度,ans開最大長度的memory。都先從字串尾開始檢查,其中,-'0'為字元轉整數,+ '0'為整數轉字元。如全部計算完但仍需進位,就直接給定為'1',如不需進位,就將指標移往下一項即可跳過空項即可。 ```Cin= //2022_03_30 char * addBinary(char * a, char * b){ int i = 0, size = 0, la = strlen(a), lb = strlen(b), pls = 0; char *opa = a + la - 1, *opb = b + lb - 1; size = la > lb ? la+1 : lb+1; char *ans = (char*)malloc(sizeof(char)*(size+1)); ans[size--] = '\0'; while(opa >= a || opb >= b){ if(opa >= a && opb >= b){ ans[size] = ((*opa - '0') + (*opb - '0') + pls) % 2 + '0'; pls = ((*opa - '0') + (*opb - '0') + pls) / 2; } else if(opa >= a){ ans[size] = ((*opa - '0') + pls) % 2 + '0'; pls = ((*opa - '0') + pls) / 2; } else { ans[size] = ((*opb - '0') + pls) % 2 + '0'; pls = ((*opb - '0') + pls) / 2; } opa--; opb--; size--; } if(size == 0){ if(pls){ans[size] = '1';} else{ans++;} } return ans; } ``` ## Link https://leetcode.com/problems/add-binary/ ###### tags: `Leetcode`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up