给你写了一个Python的,C++同理,我没有做字符串格式判断,你写的时候加上吧:
dic = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6': 6, '7': 7, '8': 8, '9': 9}
def to_int(int_str: str)-> int:
if int_str[0] == '-':
num = char_to_int(int_str[1:], len(int_str) - 2)
return 0 - num
num = char_to_int(int_str, len(int_str) - 1)
return num
def char_to_int(int_str: str, index: int):
key = int_str[index]
num = dic[key]
if index == 0:
return num
return char_to_int(int_str, index - 1) * 10 + num
if __name__ == "__main__":
result = to_int('1234')
print(result) # 1234