-
Sum binary numbers
Hello:
I wrote the following code to sum two binary numbers of the same length:
Code:
public class BinarySum {
public static void main(String[] args) {
int[] a = {0,1,1,1,1,1};
int[] b = {0,1,1,0,1,1};
int[] c = new int[a.length + 1];
int n = a.length + 1;
int m = a.length;
int aux = 0;
int i;
for(i=1 ; i <= m; i++)
{
if(a[m - i] + b[m - i] == 2)
{
c[n-i]= 0 + aux;
aux = 1;
continue;
}
else
{
if(a[m - i] + b[m - i] + aux == 2)
{
c[n-i] = 0;
aux=1;
continue;
}
else
{
c[n-i] = a[a.length - i] + b[b.length - i] + aux;
aux=0;
}
}
}
if(aux == 1)
c[0]=1;
else
c[0]=0;
for(i = 0 ; i < c.length ; i++)
System.out.print(c[i]);
}
}
I feel it cant be shorter, i mean a way more intelligent to accomplish the task.
Anyone have another idea?
Thanks.
-
Code:
for ndx = end downto 0
s = a[ndx] + b[ndx] + carry
sum[ndx + 1] = s % 2
carry = s / 2
sum[0] = carry
or something...
-
I see thats a very shorter way.
Thanks.
-
You're welcome. It's just a pseudocode description of the ordinary way we do addition (with 10 for 2): "mod" and "div" are actually old friends although they're not usually given names when teaching children to add.