67. Add Binary, 67 addbinary

Source: Internet
Author: User

67. Add Binary, 67 addbinary

Given two binary strings, return their sum (also a binary string ).

For example,
A ="11"
B ="1"
Return"100".

Question: Calculate the sum of two binary strings, and the result must be output as a binary string.

1 char * addBinary (char * a, char * B) {2 int I = strlen (a)-1; 3 int j = strlen (B)-1; 4 int c = 0; 5 char temp; 6 char * p = (char *) malloc (I> j? I + 3: j + 3); // allocate string space 7 char * s = p; 8 while (I> = 0 | j> = 0 | c = 1) 9 {10 c + = I> = 0? A [I --]-48: 0; // each character in the string is added with 11 c + = j> = 0? B [j --]-48: 0; 12 * s ++ = c % 2 + 48; 13 c = c/2; // carry 14} 15 * s = '\ 0' each time based on the c value; 16 I = 0; 17 j = strlen (p)-1; 18 while (I <j) // reverse string 19 {20 temp = p [j]; 21 p [j] = p [I]; 22 p [I] = temp; 23 I ++; 24 j --; 25} 26 return p; 27}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.