Java Help!!! Sorry for the dumbquestion but could someone please explain step by
ID: 667758 • Letter: J
Question
Java Help!!! Sorry for the dumbquestion but could someone please explain step by step how this is working...
public static int[] multiplyArrayDigits(int[] num1, int[] num2) {
int[] result = new int[num1.length + num2.length];//space for new number
int carry = 0;
int set = 0;
for (int i = num1.length - 1; i >= 0; i--) { //scans first number
int temp = result.length - 1 - set;
for (int j = num2.length - 1; j >= 0; j--) { //length of second number
int sum = result[temp] + (num1[i] * num2[j]) + carry;
result[temp] = sum % 10; // sets either 0 or 1
carry = sum / 10;
temp--;
}
if (carry > 0) { // when carry is greater is than 1
addCarry(result, temp, carry);
carry = 0;
}
set++;
}
return result;
}
Explanation / Answer
this is basically applying the concept of full adder for each bit.
public static int[] multiplyArrayDigits(int[] num1, int[] num2) {
int[] result = new int[num1.length + num2.length];//space for new number
int carry = 0; //setting initial carry to zero
int set = 0; // to keep track of current bit. Initially set to zero.
for (int i = num1.length - 1; i >= 0; i--) { //scans first number
int temp = result.length - 1 - set; //taking the first bit in the first number)
for (int j = num2.length - 1; j >= 0; j--) { //length of second number.taking each bit one by one.
int sum = result[temp] + (num1[i] * num2[j]) + carry;Now eeach bit og the second number is multiplied by one bit from the first number starting from bit0. so bit0 will be multiplied by all the bits in the second number.
result[temp] = sum % 10; // sets either 0 or 1 // this to store result of the multiplication of each but and the carry.
carry = sum / 10;
temp--;
}
if (carry > 0) { // when carry is greater is than 1
addCarry(result, temp, carry); if carry is greate than 1 then again it is added to make sure that it becomes zero.
carry = 0;
}
set++; // incrementing it by one to increase the count
}
return result;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.