如何在字符串中添加整数,只使用两个 while 循环,一个嵌套在另一个中
How to add integers in a string, using only TWO while loops, with one nested in the other
这是问题
“标准输入由一个加法组成,正好涉及五个整数项。
例如“271+9730+30+813+5”
我需要添加所有这些,同时最多只使用两个 while 循环,一个在另一个循环中。
我只允许使用诸如
if/else
而
不能为此使用列表
我尝试将第一个数字保存为 "x",然后将第二个数字保存为 "y" 并添加它,然后在最后重新启动循环,并剪切字符串以排除第一个两个数字
#!/usr/bin/env python
s = raw_input()
i = 0
y = 0
while i < len(s) and s[i] != "+":
i = i + 1
x = s[:i]
if i < len(s):
j = i + 1
while j < len(s) and s[j] != "+":
j += 1
y = s[i + i:j]
s = s[j:]
i = 0
你需要从量级的角度来思考。每移动一个位置而没有击中“+”,您就会将第一个数字的值增加 10 倍。
result=0
s="271+9730+30+813+5"
spot=0
dec=0
i=0
while spot < 4 and i < len(s):
if s[0] == '+':
spot+=1;
s=s[1:];
if s[i] == '+':
result = (result) + (int(s[0])*(10**(dec-1)));
s=s[1:];
i=0;
dec=0;
print s
print result
else:
dec+=1;
i+=1;
result = result + int(s)
print result
编辑:或者,使用 int() 和恰好 2 个 while 循环的计算效率更高的解决方案:
result=0
s="271+9730+30+813+5"
spot=0
i=0
while spot < 4:
while s[i] != '+':
i+= 1;
result += int(s[0:i]);
s=s[i+1:];
i=0;
print "remaining string: " + s
print "current result: " + str(result)
spot+=1;
result += int(s)
print "final result: " + str(result)
这是问题 “标准输入由一个加法组成,正好涉及五个整数项。 例如“271+9730+30+813+5”
我需要添加所有这些,同时最多只使用两个 while 循环,一个在另一个循环中。
我只允许使用诸如 if/else 而
不能为此使用列表
我尝试将第一个数字保存为 "x",然后将第二个数字保存为 "y" 并添加它,然后在最后重新启动循环,并剪切字符串以排除第一个两个数字
#!/usr/bin/env python
s = raw_input()
i = 0
y = 0
while i < len(s) and s[i] != "+":
i = i + 1
x = s[:i]
if i < len(s):
j = i + 1
while j < len(s) and s[j] != "+":
j += 1
y = s[i + i:j]
s = s[j:]
i = 0
你需要从量级的角度来思考。每移动一个位置而没有击中“+”,您就会将第一个数字的值增加 10 倍。
result=0
s="271+9730+30+813+5"
spot=0
dec=0
i=0
while spot < 4 and i < len(s):
if s[0] == '+':
spot+=1;
s=s[1:];
if s[i] == '+':
result = (result) + (int(s[0])*(10**(dec-1)));
s=s[1:];
i=0;
dec=0;
print s
print result
else:
dec+=1;
i+=1;
result = result + int(s)
print result
编辑:或者,使用 int() 和恰好 2 个 while 循环的计算效率更高的解决方案:
result=0
s="271+9730+30+813+5"
spot=0
i=0
while spot < 4:
while s[i] != '+':
i+= 1;
result += int(s[0:i]);
s=s[i+1:];
i=0;
print "remaining string: " + s
print "current result: " + str(result)
spot+=1;
result += int(s)
print "final result: " + str(result)