LeetCode Online Judge 題目C# 練習 - Add Binary
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 }
代碼分析:
這么簡(jiǎn)單?我想面試的時(shí)候面試官不會(huì )讓你用這兩個(gè)微軟已經(jīng)幫你寫(xiě)好的方法吧。
Convert.ToInt32(string value, int fromBase), 這是Convert類(lèi)里面靜態(tài)方法ToInt32()的一個(gè)overloadding, 參數value是要轉換的字符串,fromBase是進(jìn)制,2 : Binary, 8: Octal, 10: Deciaml, 16: Hexadecimal.
Convert.ToString(int value, int toBase),同上,只不過(guò)是由整形轉換為二進(jìn)制字符串.
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 }
代碼分析:
要注意的幾點(diǎn):
1. 最低位在右邊,所有我們從右往左加,從Length - 1到0。
2. 我用了StringBuilder,它使在字符串最前面插入字符更簡(jiǎn)單,當然我們也可以用一個(gè)char[] 數組,在后面加,最后來(lái)個(gè)reverse,然后轉換成string。
3. 我這里碰到非'0' && 非'1'字符,我會(huì )拋出一個(gè)exception, 但是這里應該更面試官商量,看他想怎么處理。
4. 別忘記了最后一個(gè)進(jìn)位。