Add Binary

Description:

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

For example,
a = "11"
b = "1"
Return "100".

Code:

 1     string addBinary(string a, string b) {

 2     //4ms

 3     const char * shortStr = (a.size()<=b.size())?a.c_str():b.c_str();

 4     const char * longStr = (a.size()>b.size())?a.c_str():b.c_str();

 5     int lenShort = strlen(shortStr);

 6     int lenLong = strlen(longStr);

 7     

 8     string s="";

 9     int temp;

10     int flag = 0;

11     for (int i = 0; i < lenShort; ++i)

12     {

13         temp = shortStr[lenShort-1-i]-'0'+longStr[lenLong-1-i]-'0'+ flag;

14         flag = temp/2;

15         s.insert(0,1,'0'+temp%2);

16     }

17    

18     for (int i = lenLong-1-lenShort; i >=0; --i)

19     {

20         temp = longStr[i]-'0'+flag;

21         flag = temp/2;

22         s.insert(0,1,'0'+temp%2);

23     }

24     

25     if (flag == 1)

26         s.insert(0,1,'1');

27     return s;

28     }

 

你可能感兴趣的:(binary)