0
0

数式の計算 (paizaランク C 相当)

Posted at

複数桁の計算。

eval()を使えば一発だけど、
意図的に考えるとそうではないので、
下記のように実装
でもだめだった。
そもそも、+と-を覚える順番が間違っていた。
最初の数値をそのままansにいれればいいのだが、
そうではなく数式も入れてしまってたので数値が代わってしまった。

s = input()
ans = 0
add = True
tmp = ""
for i in range(len(s)):
    if s[i] == '+':
        add = True
        ans += int(tmp)
        tmp = ""
    elif s[i] == '-':
        add = False
        ans -= int(tmp)
        tmp = ""
    else:
    #+でもーでもなければ数値として登録
        tmp += s[i]
        if i == len(s)-1: 
            if add == True:
                ans += int(tmp)
            else:
                ans -= int(tmp)
print(ans)

正しくはこう
凄くシンプル。。。。
ロジカルに考えられてないなぁ
isdigit()は数字かどうか確かめるやつ
そして最後のところ、.を付け足すやつはすごいなぁと思った。

s = input()

s += "."
add = True
ans = 0
tmp = ""
for i in s:
    if i.isdigit():
        tmp += i
    else:
        if add:
            ans += int(tmp)
        else:
            ans -= int(tmp)
        
        if i == "+":
            add = True
        else:
            add = False
        
        tmp = ""

print(ans)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0