67.Add Binary
题目链接:https://leetcode.com/problems/add-binary/description/
题目大意:给出两个二进制数,输出其相加结果,结果仍用二进制表示。
法一:直接模拟大数加法,(http://www.cnblogs.com/cing/p/7747957.html这个题也是模拟大数加法),将二进制改为十进制即可,细节之处在于string和char[]的转换以及string.trim()的使用,代码如下(耗时6ms):
1 public String addBinary(String a, String b) { 2 char[] tmpa = a.toCharArray(); 3 char[] tmpb = b.toCharArray(); 4 int lengtha = tmpa.length; 5 int lengthb = tmpb.length; 6 int length = lengtha > lengthb ? lengtha : lengthb; 7 char[] res = new char[length + 1]; 8 int flag = 0, num, t = 0, i, j; 9 for(i = lengtha - 1, j = lengthb - 1;i >= 0 && j >= 0; i--, j--) { 10 num = flag + (tmpa[i] - '0') + (tmpb[j] - '0'); 11 flag = num / 2; 12 res[t++] = (char) ((num % 2) + '0'); 13 } 14 while(i >= 0) { 15 num = flag + (tmpa[i] - '0'); 16 flag = num / 2; 17 res[t++] = (char) ((num % 2) + '0'); 18 i--; 19 } 20 while(j >= 0) { 21 num = flag + (tmpb[j] - '0'); 22 flag = num / 2; 23 res[t++] = (char) ((num % 2) + '0'); 24 j--; 25 } 26 while(flag != 0) { 27 res[t++] = (char) ((flag % 2) + '0'); 28 flag = flag / 2; 29 } 30 for(int k = 0; k < t / 2; k++) { 31 char tmp = res[k]; 32 res[k] = res[t - k - 1]; 33 res[t - k - 1] = tmp; 34 } 35 String s = ""; 36 for(char ch : res) { 37 s += ch; 38 } 39 return s.trim(); 40 }
法二(借鉴):与法一思想相同,只是这个代码更简洁,不用转换string和char[]即可计算,https://leetcode.com/problems/add-binary/discuss/