C# || How To Add Two Binary Strings Using C#

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to add two binary strings together using C#.

1. Add Binary – Problem Statement

Given two binary strings a and b, return their sum as a binary string.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

2. Add Binary – Solution

The following is a solution which demonstrates how to add two binary strings together.

In this solution, we start at the end of both strings, and perform basic math on each number, adding them together. If any mathematical carry over is required, that is added to the next loop iteration.

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


Was this article helpful?
👍 YesNo

Leave a Reply