Untitled
unknown
plain_text
a year ago
2.1 kB
5
Indexable
#include<stdio.h> #include<string.h> #include <stdlib.h> // đảo ngược string char* reverseStr(char *s, int n){ char* str = (char*)malloc((n+1)*sizeof(char)); int i, j = n-1; for(i = 0; i < n;i++) { str[i] = s[j]; j-= 1; } str[n] = '\0'; return str; } char* addBinary(char* a, char* b) { int lenA = strlen(a); int lenB = strlen(b); //tmp là biến nhớ, count là độ dài của string lớn hơn trong a và b int i, tmp = 0, count = 0; //reverse 2 string a = reverseStr(a,lenA); b = reverseStr(b,lenB); //Khai báo con trỏ trỏ đến string kết quả char* res; if(lenA > lenB) { int k = lenA - lenB; for(i = 0 ; i < k;i++) { b = strcat(b,"0"); } res = (char*)malloc((lenA+2)*sizeof(char)); // khởi tạo vùng nhớ cho res. count = lenA; } else if(lenB > lenA) { int k = lenB - lenA; for(i = 0 ; i < k;i++) { a = strcat(a,"0"); } res = (char*)malloc((lenB+2)*sizeof(char)); // khởi tạo vùng nhớ cho res. count = lenB; } else{ count = lenA; res = (char*)malloc((lenB+2)*sizeof(char)); // khởi tạo vùng nhớ cho res. } // thực hiện phép cộng for(i = 0;i<count;i++) { if(a[i] == b[i] && a[i] == '1') { res[i] = '0'; if(tmp == 1) { res[i] = 1; } tmp = 1; } else if(a[i] == b[i] && a[i] == '0') { res[i] = '0'; if(tmp == 1) { res[i] = '1'; } tmp = 0; } else if(a[i] == '1' && b[i] == '0' || a[i] == '0' && b[i] == '1') { res[i] = '1'; if(tmp == 1){ res[i] = '0'; } } } // nếu biến nhớ vẫn bằng 1 thì vị trí cuối của res thêm '1'. if(tmp == 1) { res[count] = '1'; res[count+1] = '\0'; } else{ res[count] = '\0'; } // giải phóng bộ nhớ free(a); free(b); res = reverseStr(res,strlen(res)); return res; } int main() { char a[100] = "1010"; char b[100] = "1011"; printf("%s", addBinary(a,b)); return 0; }
Editor is loading...
Leave a Comment