This question has already been answered:

Could you tell me how to write a code to multiply two binary numbers? It is necessary to multiply them, therefore, through a translation of 10 ss will not work.

Reported as a duplicate by members aleksandr barakin , Alex , user194374, Denis Bubnov , Qwertiy 2 Dec '16 at 10:41 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • In what form are they represented? - Harry
  • in the sense of? I enter two dozen. I convert numbers from to binary and must multiply them. - Roman
  • What does "translate into binary" mean to you? - Harry
  • @Harry well, I represent them in the form of ones and zeros. - Roman
  • 7
    It's a string, not an array ... well, never mind. Look here - here they are just engaged in multiplying the numbers written in strings. Consider only that your multiplication table is much shorter :), and when adding 1 + 1 = 10. - Harry

1 answer 1

Well, hold on ... I didn’t, as there, do - worked without intermediate arrays, straight with strings ...

string mul(const string& a, const string& b) { string r(a.length()+b.length()-1,'0'); for (int i = a.length()-1; i >= 0; i--) { for (int j = b.length()-1; j >= 0; j--) { r[i+j] += (a[i] != '0' && b[j] != '0'); } } for (int i = r.length()-1; i > 0; i--) { r[i-1] += (r[i]-'0')/2; r[i] = (r[i]-'0')%2 + '0'; } while(r[0] > '1') { r = "0" + r; r[0] += (r[1]-'0')/2; r[1] = (r[1]-'0')%2 + '0'; } return r; } int main(int argc, const char * argv[]) { cout << mul("1001","1001") << endl; cout << mul("101","111") << endl; cout << mul("1000","101") << endl; } 
  • I apologize for asking a stupid question, but could you explain to me why here r [i + j] + = (a [i]! = '0' && b [j]! = '0'); We write! = '0'? I’m just doing a similar program just for addition and division, and I don’t understand why it doesn’t work for me ... - Roman
  • @Roman Well, just there will be a unit added only when producing units. Those. when a[i] and b[j] are units. I just preferred to compare everywhere with zero. - Harry
  • that is, for addition it will be necessary to write: r [i] + = (a [i] == '1' || b [i] == '1')? Suppose that a and b are of the same length - Roman
  • In addition, you need to take into account transfers. - Harry