/**
* @author LemonLin
* @Description :StringaddBinary
* @date 2019/6/2-21:41
*
* 題目:Given two binary strings, return their sum (also a binary string).
* The input strings are both non-empty and contains only characters 1 or 0.
*
* 翻譯:
* 給定兩個二進制字符串,返回他們的和(用二進制表示)。
* 輸入爲非空字符串且只包含數字 1 和 0。
*
* Example 1:
* Input: a = "11", b = "1"
* Output: "100"
* Example 2:
* Input: a = "1010", b = "1011"
* Output: "10101"
*
* 思路:
* 考慮將字符串轉換爲數字進行處理。每個字符串從後往前遍歷,一個一個字符進行處理,同時注意進位的處理
* 1、用兩個指針分別指向a和b的末尾,從後往前遍歷,然後每次取出一個字符,轉爲數字,若無法取出字符
* 則按0處理。
* 2、定義進位carry,初始化爲0,將從a,b取出的單個字符和carry進位三者加起來,對2取餘即爲當前位的數字,
* 對2取商即爲當前進位的值,記得最後還要判斷下carry,如果爲1的話,要在結果最前面加上一個1.
*
* 難點:獲得每個索引位置的數值之後怎麼拼接起來,比如從後往前獲得的數值是1,0,1,1.怎麼把這四個數字拼成
* 1101
* 解答:這裏直接用stringbuilder的append方法,最後再reverse反轉一下,感覺不是很優雅,暫時沒想到其他
* 辦法
*/
public class StringaddBinary {
public String addBinary(String a, String b) {
//aindex bindex 記錄字符串下標,因爲從後往前遍歷所以初始化座標是字符串的長度減一
int aindex=a.length()-1;
int bindex=b.length()-1;
int carry =0;
//設置保存結果的字符串
StringBuilder result = new StringBuilder();
//用來記錄從a,b字符串取出的單個字符的整數值
int atemp ,btemp;
//用來臨時記錄三者相加的和:
int sum =0;
while (aindex>=0 || bindex>=0){
//減字符'0'是爲了將字符轉換爲對應的整數
if (aindex < 0){
atemp =0;
}else {
atemp = a.charAt(aindex--)-'0';
}
if (bindex < 0){
btemp =0;
}else {
btemp = b.charAt(bindex--)-'0';
}
sum = carry+atemp+btemp;
result.append(sum%2);
carry = sum/2;
}
if (carry ==1){
result.append("1");
}
return result.reverse().toString();
}
public static void main(String[] args) {
String a = "1010";
String b="1011";
String result = new StringaddBinary().addBinary(a,b);
System.out.println(result);
}
}
字符串二進制求和Add Binary
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.