Thursday, 25 April 2019

Adding Binary Digit

package for_interview;

import java.util.*;
import java.util.stream.Collectors;

public class ProgramOne {

    public static void main(String[] args){

        binaryCalc();

    }

    private static void binaryCalc(){
        int a = -1, b = -1, carry = 0;
        List<Integer> sum = new ArrayList<>();

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter first value : ");
        a = sc.nextInt();
        System.out.print("Enter second value : ");
        b = sc.nextInt();

        while (a != 0 || b != 0) {

            int tempCarry = carry;
            int actualBit = -1;

            if (tempCarry == 1) {
                actualBit = ((a % 10) + (b % 10) + 1) % 2;
                carry = ((a % 10) + (b % 10)  +1) / 2;
            }else {
                actualBit = ((a % 10) + (b % 10)) % 2;
                carry = ((a % 10) + (b % 10)) / 2;

            }
            sum.add(actualBit);

            a = a / 10;
            b = b / 10;



            if (a == 0 && b == 0 && carry == 1) {
                sum.add(carry);
            }

        }


        Collections.reverse(sum);
        System.out.print("Your result : ");
        String listString = sum.stream().map(Object::toString)
                .collect(Collectors.joining(","));
        System.out.println(listString);

     
//        if you want to run multiple time then use below code otherwise remove,
//        It doesn't affect on program execution.
     
        System.out.print("Run again [Y/N] : ");
        Scanner sc1 = new Scanner(System.in);
        String sAgain = sc1.nextLine();
        if (sAgain.equalsIgnoreCase("Y")) {
            binaryCalc();
        }
    }

}