Leetcode 67. Add Binary

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

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

 

 1 public class Solution {
 2     public string AddBinary(string a, string b) {
 3         if (a == null || a.Length == 0) return b;
 4         if (b == null || b.Length == 0) return a;
 5         
 6         var sb = new StringBuilder();
 7         int shift = 0;
 8         
 9         int i = a.Length - 1, j = b.Length - 1;
10         while (i >= 0 || j >= 0)
11         {
12             if (i >= 0)
13             {
14                 shift += ((int)a[i] - (int)'0');
15                 i--;
16             }
17             
18             if (j >= 0)
19             {
20                 shift += ((int)b[j] - (int)'0');
21                 j--;
22             }
23             
24             sb.Insert(0, shift % 2);
25             shift /= 2;
26         }
27         
28         if (shift != 0) sb.Insert(0, shift % 2);
29         
30         return sb.ToString();
31     }
32 }

 

posted @ 2018-01-26 09:01  逸朵  阅读(92)  评论(0)    收藏  举报