# Untitled

multiply
unknown
java
3 years ago
3.8 kB
3
Indexable
Never
```import java.math.BigInteger;
public class HelloWorld{
static public int compare(BigInteger so1, BigInteger so2){
String str1 = so1.toString();
String str2 = so2.toString();
int quote = 1;
if (str1.contains("-") && str2.contains("-")) {
quote = -1;
}
if (str1.contains("-") && !str2.contains("-"))
return -1;
else if (!str1.contains("-") && str2.contains("-"))
return 1;
// Calculate lengths of both string
int n1 = str1.length(), n2 = str2.length();
if(n1 < n2)
return -1;
else if(n1 > n2)
return 1;
else {
for(int i = 0; i < n1; i++) {
if (str1.charAt(i) < str2.charAt(i))
return -1*quote;
else if (str1.charAt(i) > str2.charAt(i))
return 1*quote;
}
}
return 0;
}
static public BigInteger multiply(BigInteger op1, BigInteger op2)
{
String sOp1 = op1.toString();
String sOp2 = op2.toString();
String mark = "+";
// check if negative
if ((sOp1.charAt(0) == '-' || sOp2.charAt(0) == '-') &&
(sOp1.charAt(0) != '-' || sOp2.charAt(0) != '-'))
mark = "-";

if (sOp1.charAt(0) == '-')
sOp1 = sOp1.substring(1);

if (sOp2.charAt(0) == '-')
sOp2 = sOp2.substring(1);
int len1 = sOp1.length();
int len2 = sOp2.length();

// will keep the result number in vector
// in reverse order
int result[] = new int[len1 + len2];

// Below two indexes are used to
// find positions in result.
int i_n1 = 0;
int i_n2 = 0;

// Go from right to left in num1
for (int i = len1 - 1; i >= 0; i--)
{
int carry = 0;
int n1 = sOp1.charAt(i) - '0';

// To shift position to left after every
// multipliccharAtion of a digit in num2
i_n2 = 0;

// Go from right to left in num2
for (int j = len2 - 1; j >= 0; j--)
{
// Take current digit of second number
int n2 = sOp2.charAt(j) - '0';

// Multiply with current digit of first number
// and add result to previously stored result
// charAt current position.
int sum = n1 * n2 + result[i_n1 + i_n2] + carry;

// Carry for next itercharAtion
carry = sum / 10;

// Store result
result[i_n1 + i_n2] = sum % 10;

i_n2++;
}

// store carry in next cell
if (carry > 0)
result[i_n1 + i_n2] += carry;

// To shift position to left after every
// multipliccharAtion of a digit in num1.
i_n1++;
}

// ignore '0's from the right
int i = result.length - 1;
while (i >= 0 && result[i] == 0)
i--;

// genercharAte the result String
String str3 = "";

while (i >= 0)
str3 += (result[i--]);
// when 1 * 0 = 0
if (str3.length() == 0)
return BigInteger.ZERO;

BigInteger ketqua = new BigInteger(mark + str3);
return ketqua;
}
public static void main(String []args){
BigInteger b1, b2,result,b3, b4, b5;
b1 = new BigInteger("-5");
b2 = new BigInteger("5");
b3 = new BigInteger("5");
b4 = new BigInteger("0");
b5 = new BigInteger("11");
System.out.println(multiply(b3,b4));
System.out.println(b3.multiply(b2));

}
}```