43.multiply Strings
[thinking]
The exact multiplication of large Numbers tests the bitwise operation of strings. The result is cached in an int array. The advantage of using an int array is that the value of each int can be greater than 10:
public String multiply(String num1, String num2) {
int len1 = num1.length(), len2 = num2.length(), len = len1 + len2, count = 0;
int[] arr = new int[len];
for (int i = len1 - 1; i >= 0; i--) {
int bit1 = num1.charAt(i) - '0';
for (int j = len2 - 1, k = j + i + 1; j >= 0; j--, k--) {
int temp = bit1 * (num2.charAt(j) - '0') + arr[k];
arr[k] = temp % 10;
arr[k - 1] += temp/10;
}
}
String s = "";
for (int i = 0; i < arr.length; i++)
s += arr[i];
while(count < len && s.charAt(count++) == '0');
return s.substring(count - 1);
}
311/311
13 Ms Your Runtime beats 29.13 per cent of javasubmissions.
Of course, I laughed when I saw something simple and funny on the Internet:
public String multiply(String num1, String num2) {
return new BigInteger(num1).multiply(new BigInteger(num2)) + "";
}
Of course, this method doesn’t work. It’s designed to make people laugh.
Welcome to optimize!
Read More:
- How to Split numbers and strings in a strings
- Java uses regular expressions to intercept the contents between specified strings
- Implementation of multithread sequential alternate execution by using lock in Java
- Design and implementation of music website based on Java
- Can’t multiply sequence by non int of type ‘float’
- fatal error LNK1169: one or more multiply defined symbols found
- JMeter running error response code: non HTTP response code: java.lang.illegalargumentexception find and solve
- java.math.BigInteger Source code
- Python: crawler handles strings of XML and HTML
- The conversion between [Python] bytes and hex strings.
- A repeated string is composed of two identical strings. For example, abcabc is a repeated string with length of 6, while abcba does not have a duplicate string. Given any string, please help Xiaoqiang find the longest repeated substring.
- How to replace strings in VIM
- Shell removes double quotes from strings
- Implementation of tupledesc and tuple in mit6.830 lab1 / exercise 1
- Python switch / case statement implementation method
- Implementation of Python switch / case statements
- [jQuery] jQuery operates on JSON strings or JSON objects
- Java was started but returned exit code = 13
- Square root of X (implementation of binary search)
- Implementation of OpenGL rotating cube