PFT
BAN USERIt seems that the above answers are making it more complicated than it should be. To check if it is strictly from left to right, we only need to pay attention to the location of the * operators. If we have any * operator after either a + or - operator, then it is not strictly from left to right because * has the privilege. With this being said, the code would be very simple.
A sample C++ code:
class ArithmeticCheck
{
string str_to_check;
public:
ArithmeticCheck(string str): str_to_check(str){}
bool getResult()
{
unsigned long L = str_to_check.length();
int i = 0;
char operator_;
int count_operators = 0;
int count_operators_not_multiply = 0;
int operator_last_index = 0;
while (i < L)
{
if(!isdigit(str_to_check[i]))
{
operator_ = str_to_check[i];
count_operators++;
// not true if starts or ends with an operator
if(i==0 || i==L-1)
{
return false;
}
// not true if two sequential operators
if(operator_last_index == i-1)
{
return false;
}
// not true if a * found after either a + or - operation
if( (count_operators>1) && (operator_=='*') && (count_operators_not_multiply>=1))
{
return false;
}
if(operator_ != '*')
{
count_operators_not_multiply++;
}
operator_last_index = i;
}
i++;
}
return true;
}
};
int main()
{
string str = "99*8*5*48*3";
ArithmeticCheck a(str);
cout << "The result: " << a.getResult() << endl;
return 0;
}
You can create an 2D array storing the status of all indices of the original 2D array. Initiate it will all 0's. Run the loop and update the status array for two conditions:
- PFT May 24, 20151. if a MP is found, update the status of MP to +1, indicating a MP, and more importantly, update the surrounding status all to -1 so that those locations will not be checked
2. if a MP is not found, do nothing