Given two binary strings, return their sum (also a binary string).
For example,
a = "1101" // 13
b = "1000" // 8
Return “1101000”. // 104
Solution: implement Binary add to perform multication
For example,
a = "1101" // 13
b = "1000" // 8
Return “1101000”. // 104
Solution: implement Binary add to perform multication
static int MultipleWithoutOperator(int num, int multiplier) { StringBuilder sb = new StringBuilder(); string binary = Convert.ToString(num, 2); string binaryMultiplier = Convert.ToString(multiplier, 2); string temp = ""; for (int i = binaryMultiplier.Length-1, j=0;i >= 0;i--,j++){ if (binaryMultiplier[i]=='1') { if (string.IsNullOrEmpty(temp)) { temp = binary.PadRight(binary.Length + j, '0'); } else { temp = BinaryAdd(temp, binary.PadRight(binary.Length + j, '0')); } } } return Convert.ToInt32(temp, 2); } static string BinaryAdd(string a, string b) { int carryover = 0; StringBuilder stringBuilder = new StringBuilder(); for (int startA = a.Length - 1, startB = b.Length - 1; startA >= 0 || startB >= 0; startA--, startB--) { int curA = startA >= 0 ? a[startA] - '0' : 0; int curB = startB >= 0 ? b[startB] - '0' : 0; int sum = curA + curB + carryover; if (sum > 1) { stringBuilder.Insert(0, sum % 2); carryover = 1; } else { stringBuilder.Insert(0, sum); carryover = 0; } } if (carryover == 1) { stringBuilder.Insert(0, '1'); } return stringBuilder.ToString(); }
留言
張貼留言