Leetcode 67. Add Binary -- 給定兩個01字串,求和,輸出結果字串
阿新 • • 發佈:2019-01-14
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"
方法1:
/** * <p>Title: </p> * <p>Description: </p> * * @CreateTime 2019/1/10 22:01 */ public class Leetcode_67_AddBinary { public static void main(String[] args) { // Integer a = Integer.parseInt("11", 2);//3 // System.out.println(Integer.toBinaryString(a));//11 Leetcode_67_AddBinary leetcode_67_addBinary = new Leetcode_67_AddBinary(); // String result = leetcode_67_addBinary.addBinary("111001", "1");//111010 String result = leetcode_67_addBinary.addBinary("111", "1");//1000 System.out.println(result); } /** * 3 ms, faster than 92.93% * @param a * @param b * @return */ public String addBinary(String a, String b) { int inc = 0; int aLength = a.length(); int bLength = b.length(); char aC; char bC; int maxLength = Math.max(aLength, bLength); int[] values = new int[maxLength + 1];//最大隻會比最大值的位數大1位 for (int i = 0; i < maxLength; i++) { if (i < aLength) { aC = a.charAt(aLength - 1 - i); } else { aC = '0'; } if (i < bLength) { bC = b.charAt(bLength - 1 - i); } else { bC = '0'; } if (aC == '1' && bC == '1') { values[i] = 0 + inc; inc = 1; } if ((aC == '0' && bC == '1') || (aC == '1' && bC == '0')) { values[i] = 1 + inc; if (values[i] == 2) { values[i] = 0; inc = 1; } else { values[i] = 1; inc = 0; } } if (aC == '0' && bC == '0') { values[i] = 0 + inc; inc = 0; } }//for if (inc == 1) {//如果計算完所有位時仍有進位,則最高位需要設定為1 values[maxLength] = 1; } else {//如果計算完所有位時沒有進位,則最高位是0,maxLength自動減1,遍歷時不再輸出該位 maxLength = maxLength - 1;//說明最高位是0 } StringBuilder sb = new StringBuilder(); for (int i = maxLength; i >= 0; i--) { sb.append(values[i]); } return sb.toString(); } /** * 如果 a b 是很長的 01 字串,會直接報錯 * * @param a * @param b * @return */ public String addBinary2(String a, String b) { Long c = Long.parseLong(a, 2); Long d = Long.parseLong(b, 2); String s = Long.toBinaryString(c + d); return s; } /** * 如果 a b 是很長的 01 字串,會直接報錯 * * @param a * @param b * @return */ public String addBinary3(String a, String b) { Integer c = Integer.parseInt(a, 2); Integer d = Integer.parseInt(b, 2); String s = Integer.toBinaryString(c + d); return s; } }
方法2:
待續