Created
September 23, 2020 07:36
-
-
Save mashimom/16f273f86254bd4a9a144bb74fdca890 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//* | |
// Target is to take strings representing binary numbers parcels, | |
// sum them (binary fashion) and return string representing the resulting binary number | |
// for the reference same code is one line in Clojure, | |
// which also works for arbritary number of parcels but it is limited by integer representation: | |
// <pre>(defn bin-sum [bns] (Integer/toString (apply + (map parse-bin bns)) 2))</pre> | |
//* | |
class Solution { | |
public String addBinary(String a, String b) { | |
int minLength = a.length() < b.length() ? a.length() : b.length(); | |
int maxLength = a.length() > b.length() ? a.length() : b.length(); | |
//padding 0s | |
StringBuilder pad = new StringBuilder(); | |
while(pad.length() < (maxLength - minLength)) { | |
pad.append('0'); | |
} | |
if(a.length()==minLength) { | |
a = pad.append(a).toString(); | |
} else { | |
b = pad.append(b).toString(); | |
} | |
// System.out.println(a); | |
// System.out.println(b); | |
//real work | |
int carry = 0; | |
StringBuilder r = new StringBuilder(); | |
for(int i = maxLength-1; i >=0; i--) { | |
// System.out.print(i+"-"); | |
if(carry==0) { | |
if(a.charAt(i)=='0' && b.charAt(i)=='0') { | |
r.append('0'); | |
} else if(a.charAt(i)=='1' && b.charAt(i)=='0') { | |
r.append('1'); | |
} else if(a.charAt(i)=='0' && b.charAt(i)=='1') { | |
r.append('1'); | |
} else if(a.charAt(i)=='1' && b.charAt(i)=='1') { | |
r.append('0'); | |
carry = 1; | |
} | |
} else { | |
if(a.charAt(i)=='0' && b.charAt(i)=='0') { | |
r.append('1'); | |
carry=0; | |
} else if(a.charAt(i)=='1' && b.charAt(i)=='0') { | |
r.append('0'); | |
} else if(a.charAt(i)=='0' && b.charAt(i)=='1') { | |
r.append('0'); | |
} else if(a.charAt(i)=='1' && b.charAt(i)=='1') { | |
r.append('1'); | |
} | |
} | |
} | |
if(carry==1) { | |
r.append('1'); | |
} | |
return r.reverse().toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment