首页 > 代码库 > Add Binary
Add Binary
Question:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
Solution:
1 #define MAX_STR_LEN (1000) 2 void add_binary(char *s, char *s1, char *s2) 3 { 4 int i; 5 int l, l1, l2; 6 int tmp; 7 char x[ MAX_STR_LEN ]; 8 9 l1 = strlen(s1);10 l2 = strlen(s2);11 l = 0;12 tmp = 0;13 memset(x, 0x00, sizeof(x));14 while(l1 > 0 && l2 > 0)15 {16 tmp = s1[--l1] + s2[--l2] + tmp - 2 * ‘0‘; 17 switch(tmp)18 {19 case 0:20 tmp = 0;21 x[l++] = ‘0‘;22 break;23 case 1:24 tmp = 0;25 x[l++] = ‘1‘;26 break;27 case 2:28 tmp = 1;29 x[l++] = ‘0‘;30 break;31 case 3:32 tmp = 1;33 x[l++] = ‘1‘;34 break;35 default:36 printf("xxx err\n");37 break;38 }39 }40 while(l1 > 0)41 {42 tmp = s1[--l1] + tmp - ‘0‘;43 if(tmp == 0)44 {45 tmp = 0;46 x[l++] = ‘0‘;47 }48 else if (tmp == 1)49 {50 tmp = 0;51 x[l++] = ‘1‘;52 }53 else /* tmp == 2 */54 {55 tmp = 1;56 x[l++] = ‘0‘;57 }58 59 }60 while(l2 > 0)61 {62 tmp = s2[--l2] + tmp - ‘0‘;63 if(tmp == 0)64 {65 tmp = 0;66 x[l++] = ‘0‘;67 }68 else if (tmp == 1)69 {70 tmp = 0;71 x[l++] = ‘1‘;72 }73 else /* tmp == 2 */74 {75 tmp = 1;76 x[l++] = ‘0‘;77 }78 }79 if(tmp)80 x[l++] = ‘1‘;81 for(i = 0; i < l; i++)82 {83 s[l-i-1] = x[i];84 //s[i] = x[i];85 }86 }
Extension:
大数加法:
1 #define MAX_STR_LEN (1000) 2 void add_large_number(char *s, char *s1, char *s2) 3 { 4 char x[MAX_STR_LEN ]; 5 int l1, l2, l; 6 int i, tmp, carry; 7 8 l1 = strlen(s1); 9 l2 = strlen(s2);10 carry = 0;11 l = 0;12 13 while(l1 > 0 && l2 > 0)14 {15 tmp = s1[--l1] + s2[--l2] - 2 * ‘0‘ + carry;16 if(tmp < 10)17 {18 carry = 0;19 x[l++] = tmp + ‘0‘;20 }21 else22 {23 carry = 1;24 x[l++] = tmp % 10 + ‘0‘;25 }26 }27 while(l1 > 0)28 {29 tmp = s1[--l1] - ‘0‘ + carry;30 if(tmp < 10)31 {32 x[l++] = tmp + ‘0‘;33 carry = 0; 34 }35 else36 {37 x[l++] = tmp % 10 + ‘0‘;38 carry = 1; 39 }40 }41 while(l2 > 0)42 {43 tmp = s2[--l2] - ‘0‘ + carry;44 if(tmp < 10)45 {46 x[l++] = tmp + ‘0‘;47 carry = 0; 48 }49 else50 {51 x[l++] = tmp % 10 + ‘0‘;52 carry = 1; 53 } 54 }55 if(carry)56 {57 x[l++] = ‘1‘;58 }59 60 for(i = 0; i < l; i++)61 {62 s[l-i-1] = x[i];63 //s[i] = x[i];64 }65 s[l] = ‘\0‘;66 }
Add Binary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。