题目地址:https://leetcode.com/problems/add-binary/description/
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
class Solution { public String addBinary(String a, String b) { int i = a.length() - 1, j = b.length() - 1; Stack<String> stack = new Stack<String>(); int jin = 0, num_a, num_b; while (i >= 0 && j >= 0){ num_a = a.charAt(i--) == '0' ? 0 : 1; num_b = b.charAt(j--) == '0' ? 0 : 1; int temp = num_a + num_b + jin; stack.push(temp % 2 == 0 ? "0" : "1"); jin = temp >> 1; } while (i >= 0) { num_a = a.charAt(i--) == '0' ? 0 : 1; int temp; if (jin != 0) { temp = num_a + jin; } else { temp = num_a; } stack.push(temp % 2 == 0 ? "0" : "1"); jin = temp >> 1; } while (j >= 0) { num_b = b.charAt(j--) == '0' ? 0 : 1; int temp; if (jin != 0) { temp = num_b + jin; } else { temp = num_b; } stack.push(temp % 2 == 0 ? "0" : "1"); jin = temp >> 1; } if (jin != 0) { stack.push("1"); } StringBuilder str = new StringBuilder(); while (!stack.isEmpty()) { str.append(stack.pop()); } return str.toString(); } }
写了半天发现评论区的一位大佬直接用BigInteger解决了,感觉智商被碾压。。。,贴上代码
import java.math.*; class Solution { public String addBinary(String a, String b) { return (new BigInteger(a, 2).add(new BigInteger(b, 2))).toString(2); } }
========================================Talk is cheap, show me the code=======================================