Skip to content

Instantly share code, notes, and snippets.

@monir-zaman
Created March 14, 2022 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monir-zaman/d406c16aa8e550f7d37183993f931437 to your computer and use it in GitHub Desktop.
Save monir-zaman/d406c16aa8e550f7d37183993f931437 to your computer and use it in GitHub Desktop.
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