题解 | #二进制求和#
二进制求和
https://www.nowcoder.com/practice/1620262056c24c0e96de32fb261703d0
using System;
using System.Collections.Generic;
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A string字符串
* @param B string字符串
* @return string字符串
*/
public string binaryAdd (string A, string B) {
if (string.IsNullOrWhiteSpace(A) && string.IsNullOrWhiteSpace(B))
return string.Empty;
if (string.IsNullOrWhiteSpace(A))
return B;
if (string.IsNullOrWhiteSpace(B))
return A;
int nMaxLen = A.Length >= B.Length ? A.Length : B.Length;
char[] cC = new char[nMaxLen];
int nAddC = 0;
for (int nIndex = nMaxLen - 1; nIndex >= 0; nIndex--) {
int nA = nIndex - (nMaxLen - A.Length) < 0 ? 0 : A[nIndex -
(nMaxLen - A.Length)] - '0';
int nB = nIndex - (nMaxLen - B.Length) < 0 ? 0 : B[nIndex -
(nMaxLen - B.Length)] - '0';
cC[nIndex] = char.Parse(((nA + nB + nAddC) % 2).ToString());
nAddC = (nA + nB + nAddC) / 2;
}
return nAddC > 0 ? nAddC.ToString() + string.Join("", cC) : string.Join("", cC);
}
}

