标签:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
char* addBinary(char* a, char* b) { int asize = strlen(a), bsize = strlen(b); int up = 0, rsize = asize; char *result; if (asize < bsize) rsize = bsize; result = malloc(rsize + 2); result[++rsize] = ‘\0‘; while (asize && bsize) { if (a[asize - 1] + b[bsize - 1] - 2 * ‘0‘ + up > 1) { result[rsize - 1] = a[asize - 1] + b[bsize - 1] - ‘0‘ + up - 2; up = 1; } else { result[rsize - 1] = a[asize - 1] + b[bsize - 1] - ‘0‘ + up; up = 0; } asize--; bsize--; rsize--; } while (asize) { result[--rsize] = a[--asize] + up; if (result[rsize] - ‘0‘> 1) { result[rsize] = ‘0‘; up = 1; } else up = 0; } while (bsize) { result[--rsize] = b[--bsize] + up; if (result[rsize] - ‘0‘> 1) { result[rsize] = ‘0‘; up = 1; } else up = 0; } if (up) { result[rsize - 1] = up + ‘0‘; return result; } else return result + 1; }
标签:
原文地址:http://www.cnblogs.com/dylqt/p/4911801.html