15、二進位制求和
阿新 • • 發佈:2018-11-16
給定兩個二進位制字串,返回他們的和(用二進位制表示)。
輸入為非空字串且只包含數字 1 和 0。
示例 1:
輸入: a = “11”, b = “1”
輸出: “100”
示例 2:
輸入: a = “1010”, b = “1011”
輸出: “10101”
我的程式碼
class Solution { public String addBinary(String a, String b) { StringBuilder sum = new StringBuilder(); int i = a.length()-1; int j = b.length()-1; int div= 0; int k; if(i >= j){ k = j; }else { k = i; } while (k >= 0) { int a1 = Integer.parseInt(Character.toString(a.charAt(i--))); // System.out.println("a1 "+a1); int b1 = Integer.parseInt(Character.toString(b.charAt(j--))); // System.out.println("b1 "+b1); if(a1+b1+div == 3 ){ div = 1; sum.append("1"); }else if (a1+b1+div ==2 ) { div = 1; sum.append("0"); }else { int x = a1 + b1 + div; sum.append(Integer.toBinaryString(x)); div = 0; } k--; } i = a.length(); j = b.length(); if( i == j){ return (div == 1)?sum.append("1").reverse().toString(): sum.reverse().toString(); } if(i < j){ int k1 = j - i; while (k1 > 0) { int b2 = Integer.parseInt(Character.toString(b.charAt(k1-1))); if ( b2+div ==2 ) { div = 1; sum.append("0"); }else { int x1 = b2+ div; sum.append(Integer.toBinaryString(x1)); div = 0; } k1--; } if(div == 1){ sum.append("1"); return sum.reverse().toString(); }else { return sum.reverse().toString(); } }else { int k2 = i - j; // System.out.println("k2 "+k2); while (k2 > 0) { // System.out.println("div "+ div); int b2 = Integer.parseInt(Character.toString(a.charAt(k2-1))); if ( b2+div ==2 ) { div = 1; sum.append("0"); }else { int x1 = b2+ div; sum.append(Integer.toBinaryString(x1)); div = 0; } k2--; } if(div == 1){ sum.append("1"); return sum.reverse().toString(); }else { return sum.reverse().toString(); } } } }
排名靠前的Java程式碼
class Solution { public String addBinary(String a, String b) { char[] aArray = a.toCharArray(); char[] bArray = b.toCharArray(); if(aArray.length>=bArray.length){ return addBinary(aArray,bArray); } return addBinary(bArray,aArray); } public String addBinary(char[] aArray,char[] bArray){ int target = 0; int initIndex = aArray.length-bArray.length; for(int i = bArray.length-1;i>=0;i--){ int temp = (int)aArray[initIndex+i]+(int)bArray[i]+ target - (int)'0'; if(temp>'1'){ aArray[initIndex+i] = (char)(temp - 2); target = 1; }else { aArray[initIndex+i] = (char)temp; target = 0; } } if(target == 0){ return String.valueOf(aArray); } for(int i = initIndex - 1;i>=0;i--){ if(aArray[i]=='0'){ aArray[i]++; return String.valueOf(aArray); } aArray[i]--; } return "1"+String.valueOf(aArray); } }