Monday 9 October 2017

Addition of two n-bit binary integers

Problem:

Consider the problem of adding two n-bit binary integers, stored in two n-element
arrays A and B. The sum of the two integers should be stored in binary form in an .n + 1 -element array C. State the problem formally and write pseudocode for
adding the two integers

Solution:

package com.basics;


public class BitArrayAddition {

public static void main(String[] args) {
int[] array1 = {0,1,0,1,1};
int[] array2 = {0,0,0,1,1};
int[] array3 = new int[5];

int carry = 0;
for (int i = array3.length - 1; i > 0; i--) {
array3[i] = (array1[i] + array2[i] + carry) % 2;
carry = (array1[i] + array2[i] + carry) / 2;
}
array3[0] = carry;
for (int i = 0; i < array3.length; i++) {
System.out.print(array3[i] + " ");
}

}

}


Output:

0 1 1 1 0

1 comment:

  1. Casino site | luckyclub.live
    Casino luckyclub site | luckyclub.live. The home of high quality casino games for everyone. From live slots to the latest Live casino games. Rating: 4 · ‎Review by LuckyClub.live

    ReplyDelete

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...