标签:
/* * 67. Add Binary
* 12.3 by Mingyang * 很简单,从后往前加,不用一开始就reverse,直接从后往前来就好了,只有StringBuffer可以reverse, * 注意n进制的加法的话就是只要加的的结果/n就是进位,%n的结果就是本位的结果 注意把carry大于0放在最后一位 * digit = a + b + carry; * carry=digit/n; * digit=digit%n; * 自己做的时候把ab两个string reverse了,这个不太好,多用了两个StringBuffer,空间占了很多 * 直接从后往前减就行了撒,不用那么做的 */ public String addBinary(String a, String b) { if (a == null || a.length() == 0) return b; if (b == null || b.length() == 0) return a; int i = a.length() - 1; int j = b.length() - 1; int carry = 0; StringBuilder res = new StringBuilder(); while (i >= 0 && j >= 0) { int digit = (int) (a.charAt(i) - ‘0‘ + b.charAt(j) - ‘0‘) + carry; carry = digit / 2; digit %= 2; res.append(digit); i--; j--; } while (i >= 0) { int digit = (int) (a.charAt(i) - ‘0‘) + carry; carry = digit / 2; digit %= 2; res.append(digit); i--; } while (j >= 0) { int digit = (int) (b.charAt(j) - ‘0‘) + carry; carry = digit / 2; digit %= 2; res.append(digit); j--; } if (carry > 0) { res.append(carry); } return res.reverse().toString(); }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5476967.html