67. Add Binary#20
Open
ryosuketc wants to merge 1 commit into
Open
Conversation
oda
reviewed
Oct 31, 2025
| public: | ||
| string addBinary(string a, string b) { | ||
| if (a.size() < b.size()) { | ||
| return addBinary(b, a); |
There was a problem hiding this comment.
string::swap
https://cplusplus.com/reference/string/string/swap/
| if (a.size() < b.size()) { | ||
| return addBinary(b, a); | ||
| } | ||
|
|
There was a problem hiding this comment.
対称性を残すならばこんなんですかね。
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;
}
nodchip
reviewed
Nov 1, 2025
| public: | ||
| string addBinary(string a, string b) { | ||
| if (a.size() < b.size()) { | ||
| return addBinary(b, a); |
There was a problem hiding this comment.
個人的には引数の順番を変えるために再帰的に関数を呼び出すのは違和感を感じます。 a と b が値渡しされており、 swap() しても呼び出し元の値は入れ替わらないため、 swap() してしまったほうが良いと思いました。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
67. Add Binary
https://leetcode.com/problems/add-binary/