问题描写叙述:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路: 採用二进制加法的思路;
代码:
public class AddBinary { //java public String addBinary(String a, String b) { if(a == null || a.trim().isEmpty()) return b.trim(); if(b == null || b.trim().isEmpty()) return a.trim(); String result = ""; int carry = 0; int alen = a.length(); int blen = b.length(); int maxLen = Math.max(alen, blen); for(int i = 0; i< maxLen; i++){ int tmpa = ((i<alen)?a.charAt(alen-1-i)-'0':0); int tmpb = ((i<blen)?b.charAt(blen-1-i)-'0':0); int sum = tmpa+tmpb+carry; if(sum >=2){ result = (sum%2) + result; carry = 1; } else { result = sum + result; carry = 0; } } if(carry == 1) result = "1"+result; return result; } public static void main(String [] args){ AddBinary ab = new AddBinary(); System.out.println(ab.addBinary("11", "1")); } }