├── README.md └── addBinary.cpp /README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /addBinary.cpp: -------------------------------------------------------------------------------- 1 | string addBinary(string a, string b) { 2 | int lungime = a.size(); 3 | int suma = 0; 4 | int carry = 0; 5 | int difference = 0; 6 | string result = ""; 7 | if (a.size() != b.size()) { 8 | if (a.size() > b.size()) { 9 | lungime = a.size(); 10 | difference = a.size() - b.size(); 11 | for (int i = 1; i <= difference; i++) 12 | { 13 | b.insert(0, "0"); 14 | 15 | 16 | } 17 | } 18 | else 19 | { 20 | lungime = b.size(); 21 | difference = b.size() - a.size(); 22 | for (int i = 1; i <= difference; i++) 23 | { 24 | a.insert(0, "0"); 25 | 26 | 27 | } 28 | } 29 | } 30 | 31 | for (int i = lungime-1; i >= 0; i--) 32 | { 33 | 34 | int c, d; 35 | if (a[i] == '0') { 36 | c = 0; 37 | } 38 | else 39 | { 40 | c = 1; 41 | } 42 | if (b[i] == '0') { 43 | d = 0; 44 | } 45 | else 46 | { 47 | d = 1; 48 | } 49 | suma += (c + d + carry); 50 | if (suma == 2) { 51 | result = result + '0'; 52 | if (c != 0 && d != 0) { 53 | carry = 1; 54 | } 55 | suma = 0; 56 | } 57 | else if(suma==1){ 58 | result = result + '1'; 59 | carry = 0; 60 | suma = 0; 61 | } 62 | else if (suma == 3) { 63 | result = result + '1'; 64 | carry = 1; 65 | suma = 0; 66 | } 67 | else if (suma == 0) { 68 | result = result + '0'; 69 | carry = 0; 70 | suma = 0; 71 | } 72 | } 73 | if (carry != 0) { 74 | result = result + '1'; 75 | } 76 | reverse(result.begin(), result.end()); 77 | return result; 78 | } 79 | --------------------------------------------------------------------------------