Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7a0f705

Browse files
authored
Merge pull requestneetcode-gh#1943 from MHamiid/patch-22
Create 0067-Add-Binary.cpp
2 parents5238136 +6187f68 commit7a0f705

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎cpp/0067-Add-Binary.cpp‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
classSolution {
2+
public:
3+
stringaddBinary(string a, string b) {
4+
string res;
5+
int maxLen = a.size() > b.size() ? a.size() : b.size();
6+
unsignedint carry =0;
7+
8+
for(int i =0; i < maxLen; i++)
9+
{
10+
unsignedint bitA = i < a.size() ? a[a.size() - i -1] -'0' :0;
11+
unsignedint bitB = i < b.size() ? b[b.size() - i -1] -'0' :0;
12+
13+
unsignedint total = bitA + bitB + carry;
14+
char sum ='0' + total %2;
15+
carry = total /2;
16+
17+
// Add to the beginning of the string
18+
res.insert(0,1, sum);
19+
}
20+
21+
if(carry)
22+
{
23+
res.insert(0,1,'1');
24+
}
25+
26+
return res;
27+
}
28+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp