题解 | #二进制求和#
二进制求和
https://www.nowcoder.com/practice/1620262056c24c0e96de32fb261703d0
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A string字符串
* @param B string字符串
* @return string字符串
*/
string binaryAdd(string A, string B) {
// write code here
int len1 = A.size(), len2 = B.size();
int cap = 0;
int i = len1 - 1, j = len2 - 1;
string ans = "";
while (i >= 0 || j >= 0) {
int a = (len1 - i <= len1) ? A[i]-'0':0;
int b = (len2 - j <= len2) ? B[j]-'0':0;
i--, j--;
int t = a + b + cap;
ans = to_string(t%2) + ans;
cap = t / 2;
}
if (cap) {
ans = "1" + ans;
}
return ans;
}
};
老板电器公司氛围 197人发布