码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 67. Add Binary

时间:2018-01-26 11:07:24      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:tco   shift   span   post   example   code   blog   length   return   

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

标签:tco   shift   span   post   example   code   blog   length   return   

原文地址:https://www.cnblogs.com/liangmou/p/8358028.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!