프로그래머스 120885 이진수 더하기

1 개요[ | ]

프로그래머스 120885 이진수 더하기

2 C++[ | ]

#include <string>
#include <vector>

using namespace std;

string solution(string bin1, string bin2) {
    int a=0, b=0;
    for(char ch: bin1) {
        a *= 2;
        a += (ch == '1');
    }
    for(char ch: bin2) {
        b *= 2;
        b += (ch == '1');
    }
    int c = a + b;
    string ret = "";
    while(c > 0) {
        ret = to_string(c%2) + ret;
        c /= 2;
    }
    return ret.empty() ? "0" : ret;
}
#include <string>
#include <vector>

using namespace std;

string solution(string bin1, string bin2) {
    int dec1 = stoi(bin1);
    int dec2 = stoi(bin2);
    string ret = "";
    int digit, add = 0;
    while(dec1 > 0 || dec2 > 0) {
        digit = (dec1%10) + (dec2%10) + add;
        ret = to_string(digit%2) + ret;
        add = digit/2;
        dec1 /= 10;
        dec2 /= 10;
    }
    if(add == 1) {
        ret = '1' + ret;
    }
    return ret.empty()? "0": ret;
}