您的位置:首页 > 其它

算法:字符串转化为数字

2020-06-10 04:25 106 查看

题目:

输入一个字符串,输出字符串中的数字。不使用 int 或 float 函数。

方法 1:

时间复杂度: O(n)

import sys

if len(sys.argv) != 2:
print("Usage: python3 %s <a string>" % sys.argv[0])
sys.exit(1)

string = sys.argv[1]
string = string.strip()
out = 0
pre = ''

for s in string:
if s == '+':
pass
elif s == '-':
pre = '-'
elif s >= '0' and s <= '9':
out = int(s) + out*10

print('The number is: ', pre, str(out))

方法 2:可以用正则表达式判断是否为数字。

时间复杂度: O(n)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: