[LeetCode]Add Binary

来源:互联网 发布:知安天下 编辑:程序博客网 时间:2024/05/29 14:50

题目描述

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".



解题思路


将两个字符串从后向前扫描,相同位的字符变为数字后进行相加运算,需要考虑到进位和两字符串不等长的情况。


代码

public static String addBinary(String a, String b) {String result = "";if (a == null && b == null) {return null;} else {if (a == null)return b;if (b == null)return a;}        int x = 0, y = 0, add = 0;for(int i = a.length() - 1,j = b.length() - 1; i >= 0 || j >=0;i--,j--){x = 0;if (i >= 0) {x = a.charAt(i) - '0';}y = 0;if (j >= 0) {y = b.charAt(j) - '0';}result = (x + y + add) % 2 + result;add = (x + y + add) / 2;}if (add == 1) {result = 1 + result;}return result;}


0 0