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

LeetCode: Add Binary 解题报告

时间:2014-10-26 22:40:47      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   使用   java   

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

For example,
a = "11"
b = "1"
Return "100".

 

SOLUTION:

指针指到两个字符串的末尾,不断往前推进,用carry表示进位。用stringbuilder来记录结果。

使用insert(0, c)函数将加出的结果不断插入到STRINGBUILDER.

bubuko.com,布布扣
 1 public class Solution {
 2     public String addBinary(String a, String b) {
 3         if (a == null || b == null) {
 4             return null;
 5         }
 6         
 7         if (a.length() == 0) {
 8             return b;
 9         }
10         
11         if (b.length() == 0) {
12             return a;
13         }
14         
15         StringBuilder sb = new StringBuilder();
16         
17         int p1 = a.length() - 1;
18         int p2 = b.length() - 1;
19         
20         int carry = 0;
21         while (p1 >= 0 || p2 >= 0) {
22             int sum = carry;
23             if (p1 >= 0) {
24                 sum += (a.charAt(p1) - ‘0‘);
25             }
26             
27             if (p2 >= 0) {
28                 sum += (b.charAt(p2) - ‘0‘);
29             }
30             
31             char c = sum % 2 == 1 ? ‘1‘: ‘0‘;
32             sb.insert(0, c);
33             carry = sum / 2;
34             
35             p1--;
36             p2--;
37         }
38         
39         if (carry == 1) {
40             sb.insert(0, ‘1‘);    
41         }
42         
43         return sb.toString();
44     }
45 }
View Code

 

GITHUB CODE:

AddBinary.java

LeetCode: Add Binary 解题报告

标签:style   blog   http   color   io   os   ar   使用   java   

原文地址:http://www.cnblogs.com/yuzhangcmu/p/4052845.html

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