1. Problem description
In actual programming, we often encounter situations where we need to deal with large integers. Due to built-in integer types in programming languages (such asint
、long
etc.) has its limitations on representing the range. When the integers that need to be processed exceed these ranges, it cannot be directly calculated using built-in types.
The general solution is to use two non-negative integers expressed in string form.num1
andnum2
multiplication and return the result as a string.
Input Limits
1 <= , <= 200
-
num1
andnum2
It can only be composed of numbers. -
num1
andnum2
Not including any leading zeros except numbers0
Original.
2. Problem-solving ideas
To solve this problem, we can simulate the process of manual multiplication. In manual multiplication, we multiply each bit of one number with each bit of another number, then add the results and process the carry. The specific steps are as follows:
-
Special circumstances handling:if
num1
ornum2
for"0"
, then return directly"0"
。 -
Invert string: In order to facilitate calculations from low to high, we will
num1
andnum2
Reversal. -
Initialize the result array: Create a length of
() + ()
Array ofret
, used to store intermediate results. Because the result number of digits multiplied by two numbers will not exceed the sum of the digits of these two numbers. -
Multiply by bit: Use two-layer loops to
num1
Every one of them andnum2
Multiply each bit of and accumulate the result toret
The corresponding position of the array. -
Handle carry:Travel
ret
Array, add the carry of each bit to the next. - Remove leading zeros: Since the result array may have leading zeros, we need to remove them.
- Convert to string: Convert the processed result array into a string.
3. Code implementation
#include <string> #include <algorithm> class Solution { public: string multiply(string num1, string num2) { // First determine whether there is one that is 0 if(num1 == "0" || num2 == "0") return "0"; // Invert two strings to facilitate operation reverse((), ()); reverse((), ()); // The number of result digits does not exceed the sum of two strings int size = () + (); // Create an array that stores the results and initialize it to 0 int* ret = new int[size](); // Multiply strings without taking into account carry for(int i = 0; i < (); ++i) { for(int j = 0; j < (); ++j) { ret[i + j] += (num1[i] - '0') * (num2[j] - '0'); } } // Handle carry for(int i = 0; i < size - 1; ++i) { ret[i + 1] += ret[i] / 10; ret[i] = ret[i] % 10; } // Remove leading zeros int i = size - 1; while( (ret[i] == 0) && (size > 1) ) { --size; --i; } // Turn string string s = ""; (size); for(int i = size - 1; i >= 0; --i) { s += ('0' + ret[i]); } // Free dynamically allocated memory delete[] ret; return s; } };
4. Detailed code analysis
1. Special circumstances handling
if(num1 == "0" || num2 == "0") return "0";
ifnum1
ornum2
for"0"
, then their product must be"0"
, just return directly.
2. Invert the string
reverse((), ()); reverse((), ());
usestd::reverse
The function willnum1
andnum2
Invert, so that processing can be started from the low bit (the starting position of the string) in subsequent calculations.
3. Initialize the result array
int size = () + (); int* ret = new int[size]();
Build a length of() + ()
The array of integersret
, and use()
Processing value initialization, and initializing all array elements to 0.
4. Multiply by bit
for(int i = 0; i < (); ++i) { for(int j = 0; j < (); ++j) { ret[i + j] += (num1[i] - '0') * (num2[j] - '0'); } }
Using a two-layer nested loop, thenum1
Every one of them andnum2
Multiply each bit of and accumulate the result toret
The corresponding position of the array.(num1[i] - '0')
and(num2[j] - '0')
is converting characters into corresponding numbers.
5. Handle carry
for(int i = 0; i < size - 1; ++i) { ret[i + 1] += ret[i] / 10; ret[i] = ret[i] % 10; }
Traversalret
Array, carry each bit (ret[i] / 10
) Add to the next bit, and at the same time, the current bit is modulo 10 to get the final result of that bit.
6. Remove leading zeros
int i = size - 1; while( (ret[i] == 0) && (size > 1) ) { --size; --i; }
Check starting from the highest bit of the result array. If the bit is 0 and the result length is greater than 1, then the length is reduced by 1 and continue to check the previous bit.
7. Convert to string
string s = ""; (size); for(int i = size - 1; i >= 0; --i) { s += ('0' + ret[i]); }
Create an empty strings
, and usereserve
Method preallocates enough space. Then start from the highest bit of the result array, convert each bit into a character and add it to the string.s
middle.
8. Free memory
delete[] ret;
becauseret
It is a dynamically allocated array, and it needs to be used after use.delete[]
Free up memory to avoid memory leakage.
5. Complexity analysis
-
Time complexity:O ( m ∗ n ), where m mm and n nn are respectively
num1
andnum2
length. The main time overhead lies in the multiplication of two-layer nested loops bit by bit. -
Space complexity:O ( m + n ), the main spatial overhead lies in the array that stores intermediate results.
ret
。
Through the above steps, we can implement multiplication of two large integers and return the result as a string. This method simulates the process of manual multiplication, avoiding the use of the built-in large integer library and directly converting the input into integers, and is suitable for handling large integer multiplication problems beyond the range of the built-in integer type representation.
The above is the detailed explanation of the code of C++ implementing the problem of multiplication of large numbers based on strings. For more information about C++ strings implementing the multiplication of large numbers, please pay attention to my other related articles!