sandeshMC

Binary Addition

Feb 4th, 2014
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class BinaryAddition {
  4.     public static void main(String args[]) {
  5.         Scanner sc = new Scanner(System.in);
  6.         int x, y;
  7.         System.out.println("ENTER THE TWO BINARY NUMBERS : ");
  8.         x = sc.nextInt();
  9.         y = sc.nextInt();
  10.         StringBuffer s1 = new StringBuffer();
  11.         StringBuffer s2 = new StringBuffer();
  12.         StringBuffer s3 = new StringBuffer("");
  13.         while (x != 0) {
  14.             s1.append(x % 2);
  15.             x /= 2;
  16.         }
  17.         while (y != 0) {
  18.             s2.append(y % 2);
  19.             y /= 2;
  20.         }
  21.  
  22.         if (s1.length() > s2.length()) {
  23.             for (int i = 0; i < s1.length() - s2.length(); i++)
  24.                 s2.append("0");
  25.         } else {
  26.             for (int i = 0; i < s2.length() - s1.length(); i++)
  27.                 s1.append("0");
  28.         }
  29.  
  30.         int flag = 0;
  31.         for (int i = 0; i < s1.length(); i++) {
  32.             if (flag == 0) {
  33.                 if (s1.charAt(i) == '0' && s2.charAt(i) == '0')
  34.                     s3.append("0");
  35.                 if (s1.charAt(i) == '1' && s2.charAt(i) == '0')
  36.                     s3.append("1");
  37.                 if (s1.charAt(i) == '0' && s2.charAt(i) == '1')
  38.                     s3.append("1");
  39.                 if (s1.charAt(i) == '1' && s2.charAt(i) == '1') {
  40.                     flag = 1;
  41.                     s3.append("0");
  42.                 }
  43.  
  44.             } else {
  45.                 if (s1.charAt(i) == '0' && s2.charAt(i) == '0') {
  46.                     s3.append("1");
  47.                     flag = 0;
  48.                 }
  49.                 if (s1.charAt(i) == '1' && s2.charAt(i) == '0') {
  50.                     s3.append("0");
  51.                     flag = 1;
  52.                 }
  53.                 if (s1.charAt(i) == '0' && s2.charAt(i) == '1') {
  54.                     s3.append("0");
  55.                     flag = 1;
  56.                 }
  57.                 if (s1.charAt(i) == '1' && s2.charAt(i) == '1') {
  58.                     flag = 1;
  59.                     s3.append("1");
  60.                 }
  61.             }
  62.         }
  63.  
  64.         if (flag == 1)
  65.             s3.append("1");
  66.         System.out.println("SUM IS " + s3.reverse());
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment