字符串加减乘除
May 1, 2024About 2 min
加减乘除
大数相加 -415 easy
注意通过数组记录各个字符串, 同时也有注意用 carry
来记录进位, 注意 reversed 方法.
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
ptr_num1 = 0
ptr_num2 = 0
return_num = []
carry = 0
while ptr_num1 < len(num1) or ptr_num2 < len(num2) or carry == 1:
digit_1 = int(num1[len(num1) - 1 - ptr_num1]) if ptr_num1 < len(num1) else 0
digit_2 = int(num2[len(num2) - 1 - ptr_num2]) if ptr_num2 < len(num2) else 0
curr_digit = carry + digit_1 + digit_2
carry = 0 if curr_digit < 10 else 1
return_num.append(str(curr_digit % 10))
ptr_num2 += 1
ptr_num1 += 1
reversed_num = reversed(return_num)
return str("".join(reversed_num))
大数相互乘法 -43 mid
- 构造一个长度为
len(num1) + len(num2)
来放 value 数组 - 注意要去除多余的 0, 如
0011
前的两个 0, 同时还要考虑0*N
这样的情况 - 分两个循环, 一个制作
value
数组, 一个处理value
数组
class Solution:
def multiply(self, num1: str, num2: str) -> str:
ptr_num1 = 0
carry = 0
return_arr = []
value = [0 for _ in range(len(num1) + len(num2))]
while ptr_num1 < len(num1):
digit_1 = int(num1[len(num1) - ptr_num1 - 1])
for i in range(0, len(num2)):
digit_2 = int(num2[len(num2) - i - 1])
curr_digit = digit_1 * digit_2
value[-(i + 1 + ptr_num1)] += curr_digit
ptr_num1 += 1
for i in range(len(value)):
curr = len(value) - 1 - i
curr_value = value[curr] + carry
return_arr.append(str(curr_value % 10))
carry = curr_value // 10
index = 0
number_str = "".join(reversed(return_arr[index::]))
for i in range(len(number_str)):
if number_str[i] == "0":
index += 1
else:
break
if index == len(num1) + len(num2):
return "0"
return number_str[index::]
这个看着要清晰的多
function multiply(num1: string, num2: string): string {
if(num1==="0"||num2==="0"){
return "0"
}
let stack = [[]];
let num1Arr = num1.split("");
let num2Arr = num2.split("");
num1Arr = num1Arr.reverse();
num2Arr = num2Arr.reverse();
for(let i = 0;i<num1Arr.length;i++){
for(let j=0;j<num2Arr.length;j++){
if(i+j>=stack.length){
stack.push([]);
}
stack[i+j].push(parseInt(num1Arr[i])*parseInt(num2Arr[j]))
}
}
let sum = "";
for (let i = 0;i < stack.length-1;i++){
let curSum = stack[i].reduce((prev,curr)=>prev+curr,0);
stack[i] = [curSum%10]
stack[i+1].push(Math.floor(curSum/10));
}
stack.reverse();
for(let i=0;i<stack.length;i++){
sum += (stack[i].reduce((prev,curr)=>prev+curr,0)).toString();
}
return sum
}```
大数减法,
同加法, 但是要考虑出现负数的情况, 在计算前要先比较大小.
同样类型的还有非 10 进制的处理, 这里在 `curr_digit = carry + digit_1 + digit_2` 处理就好,
同时注意写两个转换函数
[Python 二进制,十进制,十六进制转换\_python二进制转10进制-CSDN博客](https://blog.csdn.net/u012063703/article/details/42609833)