leetcode [Add Binary]
阿新 • • 發佈:2018-12-24
import java.util.Vector; class Solution { public String addBinary(String a, String b) { //準備過程 String res = ""; a = reverse(a);//將字串反序好加 b = reverse(b);//將字串反序好加 int alen = a.length(); int blen = b.length(); int carry = 0; int temp = 0; Vector<Integer> vector = new Vector<Integer>(); //開始加,用一個迴圈完成,手動模擬二進位制加法 for(int i = 0; i < alen || i < blen; i++){ temp = carry;//一開始將carry加在這裡 if(i < alen){ temp += a.charAt(i) - '0';// + carry;//carry只能加一次 } if(i < blen){ temp += b.charAt(i) - '0';// + carry;//carry只能加一次 } carry = temp / 2; temp = temp % 2; vector.add(temp); } if(carry != 0) vector.add(carry); //結果處理過程 char[] trans = new char[vector.size()]; int count = vector.size() - 1; for(int x : vector){ trans[count--] = (char) (x + '0'); } res = res.valueOf(trans); return res; } //編寫的字串反序函式 public String reverse(String s){ char[] res = new char[s.length()]; for(int i = s.length() - 1; i >= 0; i--){ res[s.length() - 1 - i] = s.charAt(i); } String ss = ""; return ss.valueOf(res); } }
程式碼優化(演算法思路同“上面程式碼中的開始加,用一個迴圈完成,手動模擬二進位制加法”)
class Solution { public String addBinary(String a, String b) { StringBuilder sb = new StringBuilder(); int i = a.length() - 1, j = b.length() -1, carry = 0; while (i >= 0 || j >= 0) { int sum = carry; if (j >= 0) sum += b.charAt(j--) - '0'; if (i >= 0) sum += a.charAt(i--) - '0'; sb.append(sum % 2); carry = sum / 2; } if (carry != 0) sb.append(carry); return sb.reverse().toString(); } }