码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Add Binary

时间:2015-09-23 23:13:29      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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();
}

  

 

[LeetCode]Add Binary

标签:

原文地址:http://www.cnblogs.com/lzeffort/p/4833712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!