LeetCode -- Add Binary
Question:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Analysis:
思路一:首先将二进制字符串转化成十进制,然后十进制相加,最后再转回二进制。缺点:用int型或long型数据保存变量容易造成溢出,得不到正确结果。
思路二:直接用二进制相加,逢二进一。
Answer:
一:二进制转十进制再转二进制的思路(溢出了/(ㄒoㄒ)/~~)。
public class Solution { public String addBinary(String a, String b) { if(a.equals("") && b.equals("")) return "0"; if(a == null || a.equals("") || a.equals("0")) return b; if(b == null || b.equals("") || b.equals("0")) return a; char[] a1 = a.toCharArray(); char[] b1 = b.toCharArray(); long v1 = charToInt(a1); long v2 = charToInt(b1); long sum = v1 + v2; String res = IntToBin(sum); return res; } private static String IntToBin(long sum) { // TODO Auto-generated method stub List<Long> l = new ArrayList<Long>(); while(sum > 0) { long t = sum % 2; l.add(t); sum = sum / 2; } String res = ""; for(int i=l.size()-1; i>=0; i--) { String t = l.get(i).toString(); res = res + t; } return res; } private static int charToInt(char[] a1) { // TODO Auto-generated method stub int val = 0; for(int i=0; i<a1.length; i++) { val = val * 2 + (a1[i] - 48); } return val; } }
二。直接用二进制相加
public class Solution { public String addBinary(String a, String b) { if(a.equals("") && b.equals("")) return "0"; if(a == null || a.equals("") || a.equals("0")) return b; if(b == null || b.equals("") || b.equals("0")) return a; char[] a1 = a.toCharArray(); char[] b1 = b.toCharArray(); String res = ""; int i = a1.length - 1; int j = b1.length - 1; boolean flag = false; while(i>=0 && j>=0) { if(a1[i] == '1' && b1[j] == '1' && flag == false) { res += '0'; flag = true; i--; j--; continue; } if(a1[i] == '1' && b1[j] == '1' && flag == true) { res += '1'; flag = true; i--; j--; continue; } if(a1[i] == '0' && b1[j] == '1' && flag == true || a1[i] == '1' && b1[j] == '0' && flag == true) { res += '0'; flag = true; i--; j--; continue; } if(a1[i] == '0' && b1[j] == '1' && flag == false || a1[i] == '1' && b1[j] == '0' && flag == false) { res += '1'; flag = false; i--; j--; continue; } if(a1[i] == '0' && b1[j] == '0' && flag == true) { res += '1'; flag = false; i--; j--; continue; } if(a1[i] == '0' && b1[j] == '0' && flag == false) { res += '0'; flag = false; i--; j--; continue; } } while(i>=0) { if(a1[i] == '0' && flag == true) { res += '1'; flag = false; } else if(a1[i] == '0' && flag == false) { res += '0'; flag = false; } else if(a1[i] == '1' && flag == true) { res += '0'; flag = true; } else if(a1[i] == '1' && flag == false) { res += '1'; flag = false; } i--; } while(j>=0) { if(b1[j] == '0' && flag == true) { res += '1'; flag = false; } else if(b1[j] == '0' && flag == false) { res += '0'; flag = false; } else if(b1[j] == '1' && flag == true) { res += '0'; flag = true; } else if(b1[j] == '1' && flag == false) { res += '1'; flag = false; } j--; } if(flag == true) res += '1';
StringBuffer sb = new StringBuffer(res); sb.reverse(); return sb.toString(); } }