64,685
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Context
{
public:
string input;
int output;
Context(string str_){input=str_;}
string GetInput()
{
return input;
}
void SetInput(string input_)
{
input = input_;
}
int GetOutput()
{
return output;
}
void SetOutput(int output_)
{
output = output_;
}
};
class Expression
{
public:
Expression(){}
void interpret(Context* context)
{
if (context->GetInput().length() == 0)
return;
if (context->GetInput().find(nine()))
{
context->SetOutput(context->GetOutput() + (9 * multiplier()));
context->SetInput(context->GetInput().substr(2, len-2));//自己跟了一下,错误出在这里
//input长度为1时会有问题,其实我想可能还是不太对吧,主要不太清楚Java那个substring到底怎么处理的
}
else if (context->GetInput().find(five()))
{
context->SetOutput(context->GetOutput() + (5 * multiplier()));
context->SetInput( context->GetInput().substr(1, len-1));
}
else if (context->GetInput().find(four()))
{
context->SetOutput(context->GetOutput() + (4 * multiplier()));
context->SetInput(context->GetInput().substr(2, len-2));
}
while (context->GetInput().find(one()))
{
context->SetOutput(context->GetOutput() + (1 * multiplier()));
string tempstr = context->GetInput().substr(1, len-1);
if(tempstr != "")
{
context->SetInput(context->GetInput().substr(1, len-1));
}
else
{
break;
}
}
}
virtual string one() = 0;
virtual string four() = 0;
virtual string five() = 0;
virtual string nine() = 0;
virtual int multiplier() = 0;
};
class ThousandExpression : public Expression
{
public:
ThousandExpression(){}
string one(){return "M";}
string four(){return " ";}
string five(){return " ";}
string nine(){return " ";}
int multiplier(){return 1000;}
};
class HundredExpression : public Expression
{
public:
HundredExpression(){}
string one(){return "C";}
string four(){return "CD";}
string five(){return "D";}
string nine(){return "CM";}
int multiplier(){return 100;}
};
class TenExpression : public Expression
{
public:
TenExpression(){}
string one(){return "X";}
string four(){return "XL";}
string five(){return "L";}
string nine(){return "XC";}
int multiplier(){return 10;}
};
class OneExpression : public Expression
{
public:
OneExpression(){}
string one(){return "I";}
string four(){return "IV";}
string five(){return "V";}
string nine(){return "IX";}
int multiplier(){return 1;}
};
int main()
{
// 罗马数字转阿拉伯数字
string roman = "MCMXXVIII";
Context* con = new Context(roman);
vector<Expression*> vec;
vec.push_back(new ThousandExpression());
vec.push_back(new HundredExpression());
vec.push_back(new TenExpression());
vec.push_back(new OneExpression());
vector<Expression*>::iterator pos;
for(pos = vec.begin(); pos != vec.end(); ++pos)
{
(*pos)->interpret(con);
}
delete con;
return 0;
}
context.setInput(context.getInput().substring(2));