Skip to content

67. Add Binary#20

Open
ryosuketc wants to merge 1 commit into
mainfrom
67_add_binary
Open

67. Add Binary#20
ryosuketc wants to merge 1 commit into
mainfrom
67_add_binary

Conversation

@ryosuketc
Copy link
Copy Markdown
Owner

Comment thread 67_add_binary/step2.cpp
public:
string addBinary(string a, string b) {
if (a.size() < b.size()) {
return addBinary(b, a);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread 67_add_binary/step2.cpp
if (a.size() < b.size()) {
return addBinary(b, a);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

対称性を残すならばこんなんですかね。

    std::string result;
    int i = a.size() - 1;
    int j = b.size() - 1;
    int carry = 0;
    while (i >= 0 || j >= 0 || carry) {
        int sum = carry;
        if (i >= 0) sum += a[i--] - '0';
        if (j >= 0) sum += b[j--] - '0';
        result.push_back((sum % 2) + '0');
        carry = sum / 2;
    }

Comment thread 67_add_binary/step1.cpp
public:
string addBinary(string a, string b) {
if (a.size() < b.size()) {
return addBinary(b, a);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

個人的には引数の順番を変えるために再帰的に関数を呼び出すのは違和感を感じます。 a と b が値渡しされており、 swap() しても呼び出し元の値は入れ替わらないため、 swap() してしまったほうが良いと思いました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants