首页 > 代码库 > 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 String res = ""; 4 int index1 = a.length()-1; 5 int index2 = b.length()-1; 6 int carry = 0; 7 while (index1>=0 || index2>=0){ 8 int val = 0; 9 if (index1<0){10 val = (b.charAt(index2)==‘0‘)? 0 : 1;11 val += carry; 12 index2--;13 } else if (index2<0){14 val = (a.charAt(index1)==‘0‘)? 0 : 1;15 val += carry; 16 index1--;17 } else {18 val = (a.charAt(index1)==‘0‘)? 0 : 1;19 val += (b.charAt(index2)==‘0‘)? 0 : 1;20 val += carry; 21 index1--;22 index2--;23 }24 carry = val/2;25 val = val%2;26 res = Integer.toString(val)+res;27 }28 if (carry>0) res = Integer.toString(carry)+res;29 return res;30 }31 }
Leetcode-Add Binary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。