首页 > 其他 > 详细

Leetcode 67. Add Binary

时间:2018-01-26 10:31:30      阅读:203      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!