In this blog post, I will teach you to how to write a C++ Program to Add Two Binary Strings.
Examples,
Example 1: Input: a = "10", b = "1" Output: "101" Example 2: Input: a = "1010", b = "1011" Output: "10101"
Problem Statement:
Given two binary strings s1 and s2, return their addition as a binary string.
Constraints:
➤ 1 <= s1.len, s2.len <= 104
➤ s1 and s2 consist only of ‘0’ or ‘1’ characters.
➤ Each string does not contain leading zeros (zeros that appear at the beginning of a number) except for the zero itself. Example,
- Allowed strings: “0”, “1”, “01”, “234”
- Disallowed strings: “01” , “012” , “001”
Disclaimer: Try to solve the problem yourself first otherwise it would be not worth solving this problem.
C++ Program To Add Two Binary Strings:
#include <iostream> std::string addBinary(std::string s1, std::string s2) { int carry = 0; int i = (s1.length() - 1), j = (s2.length() - 1); std::string result = ""; while ((i >= 0) || (j >= 0) || carry) { int sum = carry; if (i >= 0) { sum += (s1[i] - '0'); i--; } if (j >= 0) { sum += (s2[j] - '0'); j--; } carry = sum / 2; result = std::to_string(sum % 2) + result; } return result; } int main() { std::string s1 = "1010"; std::string s2 = "100"; std::string sum = addBinary(s1,s2); std::cout << "The sum of " << s1 << " and " << s2 << " is: " << sum << std::endl; return 0; }
Output:
The sum of 1101 and 100 is: 10001
Explanation of C Program to Add Two Binary Strings:
In the above C code, the addBinary() function takes two binary strings s1 and s2 as a parameter and returns their sum as a dynamically allocated binary string.
The addBinary() function calculates the length of the input strings and determines the maximum length for the dynamically allocated memory to store their sum. In further steps it performs the binary addition on s1 and s2, considering carry if present.
Recommended Articles for you:
- C++ Programming Courses And Tutorials.
- Range-based for loop in C++.
- C++ Program to Remove duplicates from Sorted Array.
- find the sum of natural numbers up to n terms using C program
- Get the sum of even natural numbers from 1 to n using C
- C Program to find the sum of odd natural numbers from 1 to n
- C Program to find if the given number is the sum of first n natural numbers
- C program to find the sum of first and last digit of a Number
- C++ Interview Questions with Answers.
- C program to find the sum of digits of a number.