Add Binary:二進位制加法
阿新 • • 發佈:2018-12-24
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
class Solution { public String addBinary(String a, String b) { if(a.length()<b.length()) return addBinary(b,a); StringBuilder sb = new StringBuilder(); int i = a.length()-1;//a下標 int j = b.length()-1;//b下標 int add = 0;//進位 //System.out.println(a.length()-b.length() - 1); while(i >= 0&& j >=0){ int x = Integer.parseInt(a.charAt(i)+""); int y = Integer.parseInt(b.charAt(j)+""); int temp = (x + y + add); int z = temp % 2; add = temp / 2; sb.append(z); i--; j--; } while(i>=0){ int x = Integer.parseInt(a.charAt(i)+""); int temp = (x + add); int z = temp % 2; add = temp / 2; sb.append(z); i--; } if(add!=0) sb.append(1); return sb.reverse().toString(); } }