What's wrong with this C++ solution?

  • 0

    I worked out one implementation of this problem as

    class Solution {
        string addBinary(string a, string b) {
            if (a.empty()) {
    			return b;
    		if (b.empty()) {
    			return a;
    		int bits = max(a.size(),b.size());
    		string sum;
    		char bitA, bitB;
    		int temp = 0;
    		for (int i = 0; i<bits; ++i) {
    			bitA = (a.size()-1-i>=0)?a[a.size()-1-i]:'0';
    			bitB = (b.size()-1-i>=0)?b[b.size()-1-i]:'0';
    			int a = (bitA=='1')?1:0;
    			int b = (bitB=='1')?1:0;
    			temp = a+b+temp;
    			char res = ((temp&1)==1)?'1':'0';
    			sum.insert(sum.begin(), res);
    			temp = temp>>1;
    		if (temp == 1) {
    			sum.insert(sum.begin(), '1');
    		return sum;

    The OJ told me wrong answer for this test case:


    The OJ said the results from my code was


    And the right answer should be


    Well, I then ran this test case on my machine, the answer returned on my machine was exactly same as the correct answer. How did the OJ get my answer as printed above?

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.