Topic describes
Their thinking
Since we don’t want to use BigInt to convert strings to integers, we have to consider other methods. Therefore, the double-pointer method is considered in this case.
- Use two Pointers to the end of the numeric string.
- Use the variable carry to record the carry.
- Both records enter the loop when the position of the subscript is greater than or equal to zero, or when the carry is not equal to zero.
- When the charAt API is used to retrieve the subscript characters of the string in the loop, the subtraction of the two characters becomes the number type.
- Each end of the loop moves the two Pointers one to the left.
The problem solving code
var addStrings = function(num1, num2) {
let l = num1.length - 1;
let r = num2.length - 1;
let carry = 0;
let ans = [];
while (l >= 0 || r >= 0|| carry ! = =0) {
let c1 = l >= 0 ? num1.charAt(l) - '0' : 0;
let c2 = r >= 0 ? num2.charAt(r) - '0' : 0;
let sum = c1 + c2 + carry;
ans.push(sum % 10);
carry = Math.floor(sum / 10);
l--;
r--;
}
return ans.reverse().join(' ')};Copy the code
The title to reflect
- Two numeric characters are converted to type number by subtracting them.
- You can use the string. CharAt (index) to get the character at the specified position in the string.