首页 > 代码库 > 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 }
GITHUB CODE:
AddBinary.java
LeetCode: Add Binary 解题报告
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。