首页 > 代码库 > [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"
.
https://oj.leetcode.com/problems/add-binary/
思路:类似大数计算只是进位有区别,小心carry的处理。
public class Solution { public String addBinary(String a, String b) { if (a == null || a.length() == 0) return b; if (b == null || b.length() == 0) return a; int m = a.length(), n = b.length(); StringBuilder res = new StringBuilder(); int i = m - 1, j = n - 1; int x, y, c = 0; while (i >= 0 || j >= 0) { x = (i >= 0) ? a.charAt(i) - ‘0‘ : 0; y = (j >= 0) ? b.charAt(j) - ‘0‘ : 0; res.append(x ^ y ^ c); c = (x + y + c >= 2) ? 1 : 0; i--; j--; } if (c == 1) res.append(1); return res.reverse().toString(); } public static void main(String[] args) { System.out.println(new Solution().addBinary("11", "1")); System.out.println(new Solution().addBinary("1111", "1111")); System.out.println(new Solution().addBinary("11", "")); System.out.println(new Solution().addBinary("11111111111111111111", "1")); System.out.println(new Solution().addBinary("0101", "1010")); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。