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

Add Binary

时间:2016-05-15 16:37:43      阅读:140      评论: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) {
 4             return b;
 5         }
 6         if (b == null) {
 7             return a;
 8         }
 9         if (a.length() < b.length()) {
10             String temp = a;
11             a = b;
12             b = temp;
13         }
14         int indexA = a.length() - 1;
15         int indexB = b.length() - 1;
16         int carry = 0;
17         String result = "";
18         while (indexB >= 0) {
19             int sum = (int)a.charAt(indexA) - ‘0‘ + (int)b.charAt(indexB) - ‘0‘ + carry;
20             result = String.valueOf(sum % 2) + result;
21             carry = sum / 2;
22             --indexA;
23             --indexB;
24         }
25         while (indexA >= 0) {
26             int sum = (int)a.charAt(indexA) - ‘0‘ + carry;
27             result = String.valueOf(sum % 2) + result;
28             carry = sum / 2;
29             --indexA;
30         }
31         if (carry == 1) {
32             result = "1" + result;
33         }
34         return result;
35     }
36 }

Similar Problem : LeetCode 2. Add Two Numbers

 

Add Binary

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5495276.html

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