📅  最后修改于: 2023-12-03 14:58:36.114000             🧑  作者: Mango
本题需要实现一个函数,用于计算一个字符串中的数字之和。
具体要求:
请你实现上述要求的函数,并在以下markdown代码块中给出完整的函数签名,函数实现代码以及测试样例。
def sum_of_numbers(s: str) -> int:
pass
def sum_of_numbers(s: str) -> int:
total_sum = 0
current_digit = 0
is_negative = False
for c in s:
if c.isdigit():
current_digit = current_digit * 10 + int(c)
if current_digit > (2**31 - 1):
return -1
elif c == '-':
if current_digit != 0:
total_sum += (current_digit if not is_negative else -current_digit)
current_digit = 0
if is_negative or total_sum != 0:
return -1
is_negative = True
elif c == '+':
if current_digit != 0:
total_sum += (current_digit if not is_negative else -current_digit)
current_digit = 0
if total_sum != 0:
return -1
else:
if current_digit != 0:
total_sum += (current_digit if not is_negative else -current_digit)
current_digit = 0
if c != ' ' and (is_negative or total_sum != 0):
return -1
if current_digit != 0:
total_sum += (current_digit if not is_negative else -current_digit)
return total_sum
assert sum_of_numbers("") == 0
assert sum_of_numbers("+") == 0
assert sum_of_numbers("-") == 0
assert sum_of_numbers(" ") == 0
assert sum_of_numbers("a") == 0
assert sum_of_numbers("123") == 123
assert sum_of_numbers("+123") == 123
assert sum_of_numbers("-123") == -123
assert sum_of_numbers(" +123 ") == 123
assert sum_of_numbers(" -123 ") == -123
assert sum_of_numbers("121 - 23") == -1
assert sum_of_numbers("12a34") == -1
assert sum_of_numbers("2147483648") == -1