python-2.7 - 如何在字符串中添加整数,仅使用两个 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
解决方案
你需要从数量级的角度来思考。每次您移动一个位置而不点击“+”时,您会将第一位数字的值增加 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)
推荐阅读
- visual-studio - 如何在 Winforms App Center 版本中包含 SQLite 数据库?
- go - 从 Go 使用 SIUSBXP 的正确方法是什么?
- r - 如何为解剖位置制作自定义 ggplot 地图
- unit-testing - 使用 b 按钮“to”对 vue 路由进行单元测试
- r - 如何重复对数据进行子集化并跨 R 中的列执行函数?
- amazon-web-services - 连接到私有 VPC 的 AWS Lambda 无法启动/停止 EC2 实例
- java - Spring boot 允许用户同时登录超过一次(已解决)但它无法重定向到特定网页(仍然无法正常工作)
- haskell - 变量不在范围内:x :: Picture (Haskell)
- javascript - MVC 中的 ajax 调用导致“主线程上的 xmlhttprequest 已弃用”警告
- ios - SwiftUI ForEach 视图第一次没有更新