首页 > 解决方案 > 如何在字符串中添加整数,仅使用两个 while 循环,其中一个嵌套在另一个中

问题描述

这是问题“标准输入由一个加法组成,恰好涉及五个整数项。例如,“271+9730+30+813+5”。

我需要添加所有这些,同时最多只使用两个 while 循环,一个循环。

我只允许使用 if/else while 等函数

不能为此使用列表

我已经尝试将第一个数字保存为“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

标签: python-2.7while-loopnested-loops

解决方案


你需要从数量级的角度来思考。每次您移动一个位置而不点击“+”时,您会将第一位数字的值增加 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)

推荐阅读