Problem: Make a Program to add two Binary Numbers
You are Given two Binary Numbers in string. we have to make a program to add two binary numbers given by the user.
Binary Numbers contain only two types of digits that are 0 and 1.
Input: N1 = "110", N2 = "1011"
Output: "1001" Input: N1= "111", N2 = "111" Output: "1110"
Before solving this problem "You should know how to add two binary numbers".
so Let us learn some basic concepts before solving this problem.
in Binary Number
0+1=1 carry=0
1+0=1 carry=0
0+0=0 carry=0
1+1=0 carry =1
1+1+carry(1)=1 carry=1
Here an important point that should be kept in mind before adding two binary Numbers that we have to transverse the binary string from the right side.
C Program To add Two binary numbers
here is the implementation in c language.
char* addBinary(char* a, char* b) {
int n, m;
for (n=0; *a; a++, n++) ;
for (m=0; *b; b++, m++) ;
char *sum = (char*)malloc(m>n ? m+2 : n+2), *last = sum;
int c = 0;
while (n || m || c) {
int s = c;
if (n) {
s += *(--a)-'0';
--n;
}
if (m) {
s += *(--b)-'0';
--m;
}
*last++ = (s&1)+'0';
c = s>>1;
}
*last=0;
char *start = sum, t;
while (start+1 < last) {
t = *start;
*start++=*(--last);
*last=t;
}
return sum;
}
Java Program to add Two Binary Numbers
Here is the implementation of adding two binary numbers in the java programming language.
public class Courpedia {
public String addBinary(String a, String b) {
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
StringBuilder s = new StringBuilder();
while (i >= 0 || j >= 0) {
int b1 = (i >= 0) ? Integer.parseInt(""+a.charAt(i--)):0;
int b2 = (j >= 0) ? Integer.parseInt(""+b.charAt(j--)):0;
int sum = b1 + b2 + carry;
arry = (sum == 3 || sum == 2) ? 1 : 0;
s.append((sum == 1 || sum == 3) ? 1 : 0);
}
if (carry == 1)
{
s.append(1);
}
return s.reverse().toString();
}
}
You can try some other approach to add Two binary Numbers. This is an easy question but requires a strong catch to concepts.
You May Like :