跳到主要内容

415.字符串相加

链接:415.字符串相加
难度:Easy
标签:数学、字符串、模拟
简介:给定两个字符串形式的非负整数 num1 和 num2 ,计算它们的和。

题解 1 - typescript

  • 编辑时间:2020-08-03
  • 执行用时:92ms
  • 内存消耗:40.2MB
  • 编程语言:typescript
  • 解法介绍:每个字符进行累加。
function addStrings(num1: string, num2: string): string {
const arr1 = num1.split('').reverse();
const arr2 = num2.split('').reverse();
const ans: number[] = [];
let go = 0;
while (arr1.length !== 0 && arr2.length !== 0) {
const num1 = arr1.shift() as string;
const num2 = arr2.shift() as string;
let num = parseInt(num1) + parseInt(num2) + go;
if (num >= 10) {
go = 1;
num -= 10;
} else go = 0;
ans.push(num);
}
while (arr1.length !== 0) {
let num = parseInt(arr1.shift()!) + go;
if (num >= 10) {
go = 1;
num -= 10;
} else go = 0;
ans.push(num);
}
while (arr2.length !== 0) {
let num = parseInt(arr2.shift()!) + go;
if (num >= 10) {
go = 1;
num -= 10;
} else go = 0;
ans.push(num);
}
if (go === 1) ans.push(1);
while (ans.length > 1 && ans[ans.length - 1] === 0) ans.pop();
return ans.reverse().join('');
}

题解 2 - cpp

  • 编辑时间:2023-07-17
  • 执行用时:8ms
  • 内存消耗:54.4MB
  • 编程语言:cpp
  • 解法介绍:遍历。
class Solution {
public:
string addStrings(string num1, string num2) {
if (num1.size() < num2.size()) swap(num1, num2);
string res = "";
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int i = 0, add = 0;
while (i < num1.size() || i < num2.size()) {
int num = num1[i] - '0' + add;
if (i < num2.size()) num += num2[i] - '0';
if (num >= 10) {
num -= 10;
add = 1;
} else {
add = 0;
}
res = to_string(num) + res;
i++;
}
if (add) res = "1" + res;
return res;
}
};

题解 3 - python

  • 编辑时间:2023-07-17
  • 执行用时:56ms
  • 内存消耗:15.9MB
  • 编程语言:python
  • 解法介绍:同上。
class Solution:
def addStrings(self, s1: str, s2: str) -> str:
if len(s1) < len(s2):
s1, s2 = s2, s1
res = ""
num1, num2 = list(s1), list(s2)
num1.reverse()
num2.reverse()
i = add = 0
while i < len(num1) or i < len(num2):
num = ord(num1[i]) - ord('0') + add
if i < len(num2):
num += ord(num2[i]) - ord('0')
if num >= 10:
num -= 10
add = 1
else:
add = 0
res = str(num) + res
i += 1
if add:
res = "1" + res
return res

题解 4 - rust

  • 编辑时间:2023-07-17
  • 内存消耗:2.1MB
  • 编程语言:rust
  • 解法介绍:同上。
pub fn str_to_vec(s: &String) -> Vec<char> {
s.chars().collect()
}
impl Solution {
pub fn add_strings(num1: String, num2: String) -> String {
let mut num1 = str_to_vec(&num1);
let mut num2 = str_to_vec(&num2);
num1.reverse();
num2.reverse();
if num1.len() < num2.len() {
std::mem::swap(&mut num1, &mut num2);
}
let mut res = vec![];
let mut i = 0;
let mut add = 0;
while i < num1.len() || i < num2.len() {
let mut num = num1[i].to_digit(10).unwrap() as u8 + add;
if i < num2.len() {
num += num2[i].to_digit(10).unwrap() as u8;
}
if num >= 10 {
num -= 10;
add = 1;
} else {
add = 0;
}
res.push(num + b'0');
i += 1;
}
if add != 0 {
res.push(b'1');
}
res.reverse();
String::from_utf8(res).unwrap()
}
}