首页 > 代码库 > [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"
.
思路: 采用二进制加法的思路;
代码:
public class AddBinary { //java public String addBinary(String a, String b) { if(a == null || a.trim().isEmpty()) return b.trim(); if(b == null || b.trim().isEmpty()) return a.trim(); String result = ""; int carry = 0; int alen = a.length(); int blen = b.length(); int maxLen = Math.max(alen, blen); for(int i = 0; i< maxLen; i++){ int tmpa = ((i<alen)?a.charAt(alen-1-i)-'0':0); int tmpb = ((i<blen)?b.charAt(blen-1-i)-'0':0); int sum = tmpa+tmpb+carry; if(sum >=2){ result = (sum%2) + result; carry = 1; } else { result = sum + result; carry = 0; } } if(carry == 1) result = "1"+result; return result; } public static void main(String [] args){ AddBinary ab = new AddBinary(); System.out.println(ab.addBinary("11", "1")); } }
[leetcode]Add Binary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。