通过 String模拟实现二进制的加法。和其他很多事情一样,计算加法看起来简单。至少对于人脑来说,可以说是最基本的逻辑操作。要通过编程实现,对于小白的我来说,仍然需要一番努力。
Given two binary strings, return their sum (also a binary string).
Example
a = 11
b = 1
Return 100
下面这个方法的精妙之处在于,确保 a 是长度最短的 String。这样一来,后面的算法只需要针对一种情况来处理即可,条例清晰,也更concise( 简洁 )。
public class Solution {
/**
* @param a a number
* @param b a number
* @return the result
*/
public String addBinary(String a, String b) {
// Write your code here
String result = "";
// make sure a is always the shortest
if (a.length() > b.length()) {
String temp = b;
b = a;
a = temp;
}
int lenA = a.length() - 1;
int lenB = b.length() - 1;
String rst = "";
int carries = 0;
while(lenA >= 0) {
int sum = (int)(a.charAt(lenA) - '0') + (int) (b.charAt(lenB) - '0') + carries;
rst = String.valueOf(sum % 2) + rst;
carries = sum / 2;
lenA--;
lenB--;
}
while (lenB >= 0) {
int sum = (int) (b.charAt(lenB) - '0') + carries;
rst = String.valueOf(sum % 2) + rst;
carries = sum / 2;
lenB--;
}
if (carries == 1) rst = "1" + rst;
return rst;
}
}