Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 0 padding for the shorter binary string
- // (this step isn't necessary, but easier for noob solution)
- if(b.length()>a.length()){
- int temp = b.length()-a.length();
- for(int i=0; i<temp; i++){
- a = "0"+a;
- }
- }else if(b.length()<a.length()){
- int temp = a.length()-b.length();
- for(int i=0; i<temp; i++){
- b = "0"+b;
- }
- }
- // Initializing
- int curSum = 0;
- int carry = 0;
- String result = "";
- // From the rightmost character to the leftmost
- for(int i=a.length()-1; i>=0; i--){
- curSum = (a.charAt(i)-48)+(b.charAt(i)-48)+carry;
- if(curSum==0){
- result = "0"+result;
- carry = 0;
- }else if(curSum==1){
- result = "1"+result;
- carry = 0;
- }else if(curSum==2){
- result = "0"+result;
- carry = 1;
- }else{
- result = "1"+result;
- carry = 1;
- }
- }
- if(carry==1){
- return "1"+result;
- }
- return result;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement