Leetcode 67. Add Binary

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 




以上是关于Leetcode 67. Add Binary的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode----67. Add Binary(java)

leetcode67. Add Binary

LeetCode 67. Add Binary

LeetCode 67. Add Binary

Leetcode 67. Add Binary

leetcode 67 Add Binary