标签:
问题描述:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
public class AddBinary { public String addBinary(String a, String b) { int lenA = a.length()-1; int lenB = b.length()-1; int carry = 0; StringBuffer sb = new StringBuffer(); while(lenA >= 0 && lenB >= 0) { char c = (char) ((a.charAt(lenA)-‘0‘)+(b.charAt(lenB)-‘0‘)+carry+‘0‘); if(c>=‘2‘) { c -= 2; carry = 1; } else { carry = 0; } sb.append(c); lenA --; lenB --; } if(lenA < 0) { while(lenB >= 0) { char c =(char)(b.charAt(lenB)-‘0‘+carry+‘0‘); if(c >= ‘2‘) { c -= 2; carry = 1; } else { carry = 0; } sb.append(c); lenB --; } } if(lenB < 0) { while(lenA >= 0) { char c =(char)(a.charAt(lenA)-‘0‘+carry+‘0‘); if(c >= ‘2‘) { c -= 2; carry = 1; } else { carry = 0; } sb.append(c); lenA --; } } if(carry == 1) { sb.append((char)(carry+‘0‘)); } sb.reverse(); return sb.toString(); } }
标签:
原文地址:http://www.cnblogs.com/masterlibin/p/5777582.html