首页 > 代码库 > LeetCode: Add Binary 解题报告

LeetCode: Add Binary 解题报告

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.

 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 解题报告