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

Add Binary

时间:2016-07-11 00:57:46      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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

Example

a = 11

b = 1

Return 100

分析:

这个和10进制加法一样。

total = a + b + carryover;

digit = total % 2;

carryover = total / 2;

 1 public class Solution {
 2     /**
 3      * @param a a number
 4      * @param b a number
 5      * @return the result
 6      */
 7     public String addBinary(String a, String b) {
 8         if (a == null || b == null) return null;
 9 
10         int aIndex = a.length() - 1;
11         int bIndex = b.length() - 1;
12         int carryover = 0;
13         int aValue = 0, bValue = 0;
14         StringBuilder sb = new StringBuilder();
15 
16         while(aIndex >= 0 || bIndex >= 0 || carryover != 0) {
17             if (aIndex >= 0) {
18                 aValue = a.charAt(aIndex) - 0;
19             } else {
20                 aValue = 0;
21             }
22             
23             if (bIndex >= 0) {
24                 bValue = b.charAt(bIndex) - 0;
25             } else {
26                 bValue = 0;
27             }
28             
29             int sum = aValue + bValue + carryover;
30             sb.insert(0, sum % 2);
31             carryover = sum / 2;
32             aIndex--;
33             bIndex--;
34         }
35         return sb.toString();
36     }
37 }

 

Add Binary

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5658951.html

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