BF Calculator

来源:互联网 发布:紫微排盘详批软件 编辑:程序博客网 时间:2024/06/02 19:30

題目鏈接

給一个加減法表達式, 用Brainfuck語言輸出結果.

先進行表達式解析,算出數值。
然後輸出答案。

輸出答案的思路如下:

一開始,指針指在一個「cell」上。

「.」輸出當前「cell」中數值對應的ascii字符;
「+」當前「cell」中的數值加1;
「-」當前「cell」中的數值減1;

每次輸出一個數字之後,「cell」值置0,爲下一次輸出做準備。

#include<bits/stdc++.h>using namespace std;string process(int a){    string re;    stringstream ss;    ss << a;    string orz;    ss >> orz;    for(int i = 0;i<orz.length();i++){        for(int j = 0;j<orz[i];j++) re+='+';        re+='.';        for(int j = 0;j<orz[i];j++) re+='-';    }    return re;}int main(){    string s;    cin >> s;    s+='+';    int re = 0,temp = 0,sig = 1;    for(int i = 0;i<s.length();i++){        if(s[i] == '+'){            re += sig*temp;            sig = 1;            temp =0;        }else if(s[i] == '-'){            re+=sig*temp;            sig = -1;            temp =0;        }else if(s[i] >='0'&&s[i]<='9'){            temp = temp*10 + s[i]-'0';        }    }    cout << process(re) << endl;}
原创粉丝点击