标签:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题解:二进制字符串相加
public String addBinary(String a, String b) { //c表示为进位的 int len1 = a.length()-1,len2 = b.length()-1,c=0; StringBuffer sb = new StringBuffer(); while(len1>=0 && len2>=0){ int temp = (a.charAt(len1)-‘0‘)+(b.charAt(len2)-‘0‘)+c; c = temp/2; temp = temp%2; sb.insert(0, temp+""); len1--; len2--; } while(len1>=0){ int temp = (a.charAt(len1)-‘0‘)+c; c = temp/2; temp = temp%2; sb.insert(0, temp+""); len1--; } while(len2>=0){ int temp = (b.charAt(len2)-‘0‘)+c; c = temp/2; temp = temp%2; sb.insert(0, temp+""); len2--; } //注意1,1的情况要进位 if(c==1) sb.insert(0,c+""); return sb.toString(); }
别人的短码:
public String addBinary(String a, String b) { StringBuilder sb = new StringBuilder(); int carry = 0; for(int i=a.length()-1,j=b.length()-1;i>=0 || j>=0;i--,j--){ int v1 = (i<0)?0:a.charAt(i)-‘0‘; int v2 = (j<0)?0:b.charAt(j)-‘0‘; int val = (v1+v2+carry)%2; carry = (v1+v2+carry)/2; sb.insert(0,(char)(val+‘0‘)); } if(carry == 1) sb.insert(0,‘1‘); return sb.toString(); }
标签:
原文地址:http://www.cnblogs.com/lzeffort/p/4833712.html