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
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
Casino site | luckyclub.live
ReplyDeleteCasino 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