1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public class Solution { public String addBinary(String a, String b) { int len1 = a.length(); int len2 = b.length(); int delta = Math.abs(len1 - len2); int max = Math.max(len1, len2); int[] intVal1 = new int[max]; int[] intVal2 = new int[max]; if(len1 >= len2){ for(int i = 0; i < max; i++){ intVal1[i] = Integer.parseInt(String.valueOf(a.charAt(i))); } for(int j = 0; j < max; j++){ if(j < delta){ intVal2[j] = 0; } else { intVal2[j] = Integer.parseInt(String.valueOf(b.charAt(j - delta))); } } } else { for(int i = 0; i < max; i++){ intVal1[i] = Integer.parseInt(String.valueOf(b.charAt(i))); } for(int j = 0; j < max; j++){ if(j < delta){ intVal2[j] = 0; } else { intVal2[j] = Integer.parseInt(String.valueOf(a.charAt(j - delta))); } } } StringBuilder builder = new StringBuilder(""); handle(max, 0, intVal1, intVal2, builder); return builder.reverse().toString(); } private static void handle(int max, int more, int[] val1, int[] val2, StringBuilder builder){ int temp = 0; if(max >= 1){ temp = val1[max - 1] + val2[max - 1] + more; } else { temp = val1[0] + val2[0] + more; } if(max-1 > 0){ if(temp <= 1){ builder.append(Integer.toString(temp)); handle(--max, 0, val1, val2, builder); } else { builder.append(Integer.toString(temp % 2)); handle(--max, 1, val1, val2, builder); } } else { if(temp <= 1){ builder.append(Integer.toString(temp)); } else { builder.append(Integer.toString(temp % 2)); builder.append("1"); } } } }
|