Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
題目:求2個二進制字符串的和,結果也要二進制字符串輸出。
1 char* addBinary(char* a, char* b) { 2 int i = strlen(a)-1; 3 int j = strlen(b)-1; 4 int c = 0; 5 char temp; 6 char *p = (char*)malloc(i > j ? i+3 :j+3); //分配字符串空間 7 char *s = p; 8 while(i >= 0 || j >= 0 || c == 1) 9 { 10 c += i >= 0 ? a[i--] - 48 : 0; //字符串每一位相加 11 c += j >= 0 ? b[j--] - 48 : 0; 12 *s++ = c % 2 + 48; 13 c = c/2; //根據c的值每次要進位 14 } 15 *s = '\0'; 16 i = 0; 17 j = strlen(p)-1; 18 while(i < j) //反轉字符串 19 { 20 temp = p[j]; 21 p[j] = p[i]; 22 p[i] = temp; 23 i++; 24 j--; 25 } 26 return p; 27 }