一、原題
Given two binary strings, return their sum (also a binary string). For example, a ="11"
b = "1"
Return "100"
一、中文
給定兩個二進制的字符串,返回它們的和,也是二進行制字符串。
str1 = “111”,str2=“1”最后返回的結果的是1000
先將對應的兩個二進制字符串轉換成對應的整數數組,從低位到高位進行相加,同時要考慮到最后相加還要擴展一位的情況。詳情請見代碼實現。
package code;public class LeetCode42{ public static void main(String args[]){ String str = addBinary("111", "1"); System.out.PRintln(str); } //數組表示的數字進行加一操作,數組的最高位表示的是數字的最低位 public static String addBinary(String str1, String str2) { if(str1 == null || str2 == null){ return null; }else{ int num1[] = new int[str1.length()]; int num2[] = new int[str2.length()]; for(int i = 0; i < str1.length(); i++){ num1[i] = str1.charAt(i) - '0'; } for(int j = 0; j < str2.length(); j++){ num2[j] = str2.charAt(j) - '0'; } //使num1保存比較長的數組的長度 if (num1.length < num2.length) { int[] tmp = num1; num1 = num2; num2 = tmp; } int index1 = num1.length - 1; // 字符數組ca最后一個索引下標 int index2 = num2.length - 1; // 字符數組cb最后一個索引下標 int carry = 0; // 下位的進位標識 int result; // 加載的結果 //將兩個數進行相加 while (index1 >= 0 && index2 >= 0) { result = num1[index1] + num2[index2] + carry; num1[index1] = result % 2; carry = result / 2; index1--; index2--; } //處理num1剩余的數字,也就是較長的數字的剩余的數字 while(index1 >= 0){ result = carry + num1[index1]; num1[index1] = result%2; carry = result/2; if(carry == 0){ break; } index1--; } // 將字符數組中的值轉換了字符的0或者1 for (int i = 0; i < num1.length; i++) { num1[i] += '0'; } // 不需要擴展一位 if (carry == 0) { char[] ch = new char[num1.length]; for (int i = 0; i < num1.length; i++) { ch[i] = (char) (num1[i]); } return new String(ch); }else{ char[] ch = new char[num1.length + 1]; ch[0] = '1'; for (int i = 0; i < num1.length; i++) { ch[i + 1] = (char) (num1[i]); } return new String(ch); } } }} ---------------------------------output----------------------------------1000
新聞熱點
疑難解答