Results 1 to 4 of 4
Thread: Sum binary numbers
- 12-13-2009, 07:32 AM #1
Member
- Join Date
- Nov 2009
- Posts
- 12
- Rep Power
- 0
Sum binary numbers
Hello:
I wrote the following code to sum two binary numbers of the same length:
I feel it cant be shorter, i mean a way more intelligent to accomplish the task.Java 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]); } }
Anyone have another idea?
Thanks.Last edited by Fubarable; 12-13-2009 at 07:42 AM. Reason: code tags added
- 12-13-2009, 08:09 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
Java 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...Last edited by pbrockway2; 12-13-2009 at 08:09 AM. Reason: code tags!
- 12-14-2009, 03:59 AM #3
Member
- Join Date
- Nov 2009
- Posts
- 12
- Rep Power
- 0
I see thats a very shorter way.
Thanks.
- 12-14-2009, 04:44 AM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
Similar Threads
-
Binary
By THEAniKan in forum EntertainmentReplies: 1Last Post: 01-06-2012, 10:14 AM -
Binary IO help
By kosok in forum New To JavaReplies: 2Last Post: 12-25-2008, 07:58 AM -
printing two smallest numbers from a series of numbers
By trofyscarz in forum New To JavaReplies: 2Last Post: 10-14-2008, 11:46 PM -
get binary value
By rushenas in forum New To JavaReplies: 2Last Post: 06-14-2008, 01:51 PM -
binary search
By tranceluv in forum New To JavaReplies: 10Last Post: 01-14-2008, 07:13 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks