首页 > 代码库 > [Leetcode] Add Binary
[Leetcode] Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Solution:
1 public class Solution { 2 public String addBinary(String a, String b) { 3 if(a==null) 4 return b; 5 if(b==null) 6 return a; 7 int end_a=a.length()-1; 8 int end_b=b.length()-1; 9 int carry=0;10 String result="";11 while(end_a>=0&&end_b>=0){12 int temp=(a.charAt(end_a)-‘0‘)+(b.charAt(end_b)-‘0‘)+carry;13 carry=temp/2;14 temp%=2;15 result=(temp+"")+result;16 end_a--;17 end_b--;18 }19 while(end_a>=0){20 int temp=(a.charAt(end_a)-‘0‘)+carry;21 carry=temp/2;22 temp%=2;23 result=(temp+"")+result;24 end_a--;25 }26 while(end_b>=0){27 int temp=(b.charAt(end_b)-‘0‘)+carry;28 carry=temp/2;29 temp%=2;30 result=(temp+"")+result;31 end_b--;32 }33 if(carry!=0){34 result=(carry+"")+result;35 }36 return result;37 }38 }
[Leetcode] Add Binary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。