Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class BinaryAddition {
- public static void main(String args[]) {
- Scanner sc = new Scanner(System.in);
- int x, y;
- System.out.println("ENTER THE TWO BINARY NUMBERS : ");
- x = sc.nextInt();
- y = sc.nextInt();
- StringBuffer s1 = new StringBuffer();
- StringBuffer s2 = new StringBuffer();
- StringBuffer s3 = new StringBuffer("");
- while (x != 0) {
- s1.append(x % 2);
- x /= 2;
- }
- while (y != 0) {
- s2.append(y % 2);
- y /= 2;
- }
- if (s1.length() > s2.length()) {
- for (int i = 0; i < s1.length() - s2.length(); i++)
- s2.append("0");
- } else {
- for (int i = 0; i < s2.length() - s1.length(); i++)
- s1.append("0");
- }
- int flag = 0;
- for (int i = 0; i < s1.length(); i++) {
- if (flag == 0) {
- if (s1.charAt(i) == '0' && s2.charAt(i) == '0')
- s3.append("0");
- if (s1.charAt(i) == '1' && s2.charAt(i) == '0')
- s3.append("1");
- if (s1.charAt(i) == '0' && s2.charAt(i) == '1')
- s3.append("1");
- if (s1.charAt(i) == '1' && s2.charAt(i) == '1') {
- flag = 1;
- s3.append("0");
- }
- } else {
- if (s1.charAt(i) == '0' && s2.charAt(i) == '0') {
- s3.append("1");
- flag = 0;
- }
- if (s1.charAt(i) == '1' && s2.charAt(i) == '0') {
- s3.append("0");
- flag = 1;
- }
- if (s1.charAt(i) == '0' && s2.charAt(i) == '1') {
- s3.append("0");
- flag = 1;
- }
- if (s1.charAt(i) == '1' && s2.charAt(i) == '1') {
- flag = 1;
- s3.append("1");
- }
- }
- }
- if (flag == 1)
- s3.append("1");
- System.out.println("SUM IS " + s3.reverse());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment