- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiply_String.java
More file actions
Latest commit
82 lines (73 loc) · 2.24 KB
/
Copy pathMultiply_String.java
File metadata and controls
82 lines (73 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
publicclassSolution {
publicStringmultiply(Stringnum1, Stringnum2) {
Stringresult = "0";
if (num1.equals("0") || (num2.equals("0"))) {
returnresult;
}
intlength = num2.length();
Stringbase = "";
for (inti = length-1; i >= 0; i--) {
chardigit = num2.charAt(i);
intnumDigit = digit - '0';
Stringres = multiplyByDigit(num1, numDigit) + base;
result = add(res, result);
base = base + '0';
}
returnresult;
}
privateStringmultiplyByDigit(Stringnum, intdigit) {
if (digit == 0) {
return"0";
}
Stringresult = "";
intlength = num.length();
intcarry = 0;
for (inti = length-1; i >= 0; i--) {
intnumber = num.charAt(i) - '0';
intres = number * digit + carry;
carry = res / 10;
res = res % 10;
result = res + result;
}
if (carry != 0) {
result = carry + result;
}
returnresult;
}
privateStringadd(Stringnum1, Stringnum2) {
intcarry = 0;
intpos1 = num1.length() - 1;
intpos2 = num2.length() - 1;
Stringresult = "";
while ((pos1 >= 0) && (pos2 >= 0)) {
intdigit1 = num1.charAt(pos1) - '0';
intdigit2 = num2.charAt(pos2) - '0';
intresDigit = digit1 + digit2 + carry;
carry = resDigit / 10;
resDigit = resDigit % 10;
result = resDigit + result;
pos1--;
pos2--;
}
while (pos1 >= 0) {
intdigit1 = num1.charAt(pos1) - '0';
intresDigit = digit1 + carry;
carry = resDigit / 10;
resDigit = resDigit % 10;
result = resDigit + result;
pos1--;
}
while (pos2 >= 0) {
intdigit2 = num2.charAt(pos2) - '0';
intresDigit = digit2 + carry;
carry = resDigit / 10;
resDigit = resDigit % 10;
result = resDigit + result;
pos2--;
}
if (carry != 0) {
result = carry + result;
}
returnresult;
}
}