Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
1 public static string AddBinary(string a, string b) 2 { 3 try 4 { 5 int sum = Convert.ToInt32(a, 2) + Convert.ToInt32(b, 2); 6 return Convert.ToString(sum, 2); 7 } 8 catch (Exception ex) 9 { 10 throw ex; 11 } 12 }
代码分析:
这么简单?我想面试的时候面试官不会让你用这两个微软已经帮你写好的方法吧。
Convert.ToInt32(string value, int fromBase), 这是Convert类里面静态方法ToInt32()的一个overloadding, 参数value是要转换的字符串,fromBase是进制,2 : Binary, 8: Octal, 10: Deciaml, 16: Hexadecimal.
Convert.ToString(int value, int toBase),同上,只不过是由整形转换为二进制字符串.
1 public static string AddBinaryNoConvertTo(string a, string b) 2 { 3 StringBuilder ret = new StringBuilder(); 4 int aValue, bValue, sum; 5 int carry = 0; 6 7 for(int i = a.Length - 1, j = b.Length - 1; i > -1 || j > -1; i--, j--) 8 { 9 if (i <= -1) // when i out of range, put 0 in aValue for addition 10 aValue = 0; 11 else 12 { 13 if (a[i] == '1') 14 aValue = 1; 15 else if (a[i] == '0') 16 aValue = 0; 17 else 18 throw new FormatException("Input string has invalid character"); 19 } 20 if (j <= -1) 21 bValue = 0; // when j out of range, put 0 in aValue for addition 22 else 23 { 24 if (b[j] == '1') 25 bValue = 1; 26 else if (b[j] == '0') 27 bValue = 0; 28 else 29 throw new FormatException("Input string has invalid character"); 30 } 31 32 sum = aValue + bValue + carry; 33 carry = 0; //reset carry 34 if (sum > 1) 35 { 36 carry = 1; //set carry 37 sum -= 2; 38 } 39 ret.Insert(0, sum); 40 } 41 if (carry == 1) // Don't miss the carry at the most significant bit. 42 { 43 ret.Insert(0, '1'); 44 } 45 46 return ret.ToString(); 47 }
代码分析:
要注意的几点:
1. 最低位在右边,所有我们从右往左加,从Length - 1到0。
2. 我用了StringBuilder,它使在字符串最前面插入字符更简单,当然我们也可以用一个char[] 数组,在后面加,最后来个reverse,然后转换成string。
3. 我这里碰到非'0' && 非'1'字符,我会抛出一个exception, 但是这里应该更面试官商量,看他想怎么处理。
4. 别忘记了最后一个进位。