C++ 0067.cpp
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
while (a.size() < b.size())
a += '0';
while (b.size() < a.size())
b += '0';
string result;
result.reserve(a.size() + 1);
int carry = 0;
for (int i = 0; i < a.size(); i++)
{
int sum = carry + (a[i] - '0') + (b[i] - '0');
result += '0' + (sum & 1);
carry = sum >> 1;
}
if (carry > 0)
result += '1';
reverse(result.begin(), result.end());
return result;
}
};
Difficulty
and has an acceptance rate of about 58% (4+ million submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- Math
- Simulation
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the binary sum of two strings representing non-negative binary numbers. It follows a classic approach of aligning the operands from the least significant bit, performing digit-wise addition with a carry, and finally producing the result in the correct order. The algorithm works entirely with standard library operations and avoids dynamic memory allocations beyond the reserved result buffer.
Key Steps
The first phase reverses both input strings so that indexβ―0 corresponds to the least significant bit. This enables a straightforward left-to-right traversal during addition.
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
Next, the code equalizes the lengths of the two strings by appending '0' characters to the shorter one. This guarantees that the subsequent loop can safely access a[i] and b[i] for every index.
while (a.size() < b.size())
a += '0';
while (b.size() < a.size())
b += '0';
A result string is created and its capacity is pre-allocated to accommodate the maximum possible length, which is the length of the longer operand plus one extra character for a potential final carry.
string result;
result.reserve(a.size() + 1);
The core addition loop iterates over each position, computes the sum of the corresponding bits together with the current carry, extracts the resulting bit using a bitwise AND, and updates the carry with a right shift. The resulting bit is appended to the result string.
int carry = 0;
for (int i = 0; i < a.size(); i++)
{
int sum = carry + (a[i] - '0') + (b[i] - '0');
result += '0' + (sum & 1);
carry = sum >> 1;
}
After processing all positions, a leftover carry is appended if it is non-zero, ensuring that overflow is correctly represented.
if (carry > 0)
result += '1';
Finally, the result string, which has been built in reverse order, is reversed to present the binary number in the conventional most-significant-bit-first format.
reverse(result.begin(), result.end());
return result;
Edge Cases Handled
The algorithm gracefully manages inputs of differing lengths by padding the shorter string with '0' characters, thereby eliminating the need for conditional checks inside the addition loop. When both inputs consist solely of '0' characters, the loop produces a single '0' result, and the final carry check does not add an extra digit. If the addition generates an overflow beyond the original length-such as adding "1" and "1"-the explicit carry handling appends the leading '1', yielding the correct "10" result. The use of reserve ensures that even the maximal length case (original length plus one) is accommodated without reallocation.
Performance Optimizations
Reversing the input strings in place avoids the overhead of creating auxiliary reversed copies. Length equalization through simple concatenation of '0' characters is performed only once per string, preventing repeated size checks during the main loop. Pre-allocating the result buffer with reserve eliminates incremental memory allocations as characters are appended, which can be costly in tight loops. The addition logic leverages bitwise operations (& 1 and >> 1) to extract the result bit and compute the new carry efficiently, avoiding more expensive arithmetic or conditional branching. By operating directly on character codes (a[i] - '0'), the code sidesteps the need for conversion functions, further reducing runtime overhead.
ELI5 - Simplified Explanation
Imagine you have two towers made of blocks, where each block is either a zero or a one. To add the towers together, the code first flips them over so the bottom blocks are at the very top. This makes it easier to start counting from the bottom of each pile up to the top. Because the towers might have different heights, the code fills in the shorter tower with extra zero blocks until both piles look like they are exactly the same size. Now, it looks at each pair of blocks and adds them together. If two ones are added, they become a two, which is too big, so it turns into a zero and leaves a little extra block behind that needs to be carried over to the next pair. This process continues for every single block in the towers. If there is a leftover piece at the very end, it gets added as a final block. Once everything is done, the tower is flipped back over to its original position to show the final answer.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | C# | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 66: Plus One
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality