67. Add Binary
Given two binary strings a and b, return their sum as a binary string.
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.
solution1 模拟
class Solution {
public:
string addBinary(string a, string b) {
string ans;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int n = max(a.size(), b.size()), carry = 0;
for (size_t i = 0; i < n; ++i) {
carry += i < a.size() ? (a.at(i) == '1') : 0;
carry += i < b.size() ? (b.at(i) == '1') : 0;
ans.push_back((carry % 2) ? '1' : '0');
carry /= 2;
}
if (carry) {
ans.push_back('1');
}
reverse(ans.begin(), ans.end());
return ans;
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/add-binary/solution/er-jin-zhi-qiu-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
string addBinary(string a, string b) {
int n=a.size(), m=b.size(), c=0;
if(n < m) // a前补0
a = string(m-n, '0') + a;
else // b前补0
b = string(n-m, '0') + b;
n = a.size();
for(int i=1;i<=n;i++){
int s = (b[n-i]-'0') + (a[n-i]-'0') + c; // 当前位总和
a[n-i] = '0' + (s&1); // 当前位更新
c = s/2; // 进位计算
}
return c ? '1'+a : a; // 最后还有进位则在头部补1
}
};
作者:nbgao
链接:https://leetcode.cn/problems/add-binary/solution/by-nbgao-qgew/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
solution2位运算
class Solution:
def addBinary(self, a, b) -> str:
x, y = int(a, 2), int(b, 2)
while y:
answer = x ^ y
carry = (x & y) << 1
x, y = answer, carry
return bin(x)[2:]
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/add-binary/solution/er-jin-zhi-qiu-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
int i=a.length()-1;
int j=b.length()-1;
int carry=0;
string ans="";
while(i>=0 || j>=0)
{
int t=(i>=0 ? a[i]-'0' : 0) + (j>=0 ? b[j]-'0' : 0) + carry;
carry = t/2;
ans+=(t%2)+'0';
i--;
j--;
}
if(carry)
{
ans+='1';
}
reverse(ans.begin(), ans.end());
return ans;
size_t 类型表示C中任何对象所能达到的最大长度,它是无符号整数。
它是为了方便系统之间的移植而定义的,不同的系统上,定义size_t 可能不一样。size_t在32位系统上定义为 unsigned int,也就是32位无符号整型。在64位系统上定义为 unsigned long ,也就是64位无符号整形。size_t 的目的是提供一种可移植的方法来声明与系统中可寻址的内存区域一致的长度。
string .at()用于获取指定字符
string str;
cin>>str; //str=="12345"
char ch;
ch = str.at(0);
cout<<ch; //ch=='1';
at(i),i就是想要获取的字符的下标,函数返回值为指定的字符