Created
March 14, 2022 11:18
-
-
Save monir-zaman/d406c16aa8e550f7d37183993f931437 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import java.util.Scanner; | |
public class AddBinary { | |
public static void main(String... args) { | |
Scanner scanner = new Scanner(System.in); | |
String firstSt = scanner.nextLine(); | |
String secondSt = scanner.nextLine(); | |
String result = getSummation(firstSt, secondSt); | |
System.out.println(result); | |
} | |
static String getSummation(String firstSt, String secondSt) { | |
int s1 = firstSt.length(); | |
int s2 = secondSt.length(); | |
int carry = 0; | |
int sum; | |
StringBuilder result = new StringBuilder(); | |
while (s1>0 || s2 >0) { | |
int firstCurrent = 0; | |
int secondCurrent = 0; | |
if (s1>0) { | |
s1--; | |
firstCurrent = firstSt.charAt(s1) - '0'; | |
} | |
if (s2>0) { | |
s2--; | |
secondCurrent = secondSt.charAt(s2) - '0'; | |
} | |
sum = carry + firstCurrent + secondCurrent; | |
if (sum == 3) { | |
result.insert(0, "1"); | |
carry = 1; | |
} else if (sum == 2) { | |
result.insert(0, "0"); | |
carry = 1; | |
} else if (sum == 1) { | |
result.insert(0, "1"); | |
carry = 0; | |
} else if (sum == 0) { | |
result.insert(0, "0"); | |
carry = 0; | |
} | |
} | |
if (carry ==1) result.insert(0, "1"); | |
return result.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment