Docsity

Arithmetic Expression, Assignments of Theory of Automata

Toggle sidebar
bg1
...ructure And Algorithms\Lectures\DSA\01.File_Stream\AE.cpp 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <string>
using namespace std;
bool isInteger(string x)
{
if (x.size() == 1 && (x[0] - '0') >= 0 && (x[0] - '0') <= 9)
return true;
return false;
}
bool AE(string x)
{
if (isInteger(x)) // Rule 1 : Any number
(positive, negative, or zero)
return true;
else if ((x[0] == '(' && x[x.size() - 1] == ')') || x[0] == '-') // Rule 2
{
if (x[0] == '(' && x[x.size() - 1] == ')') // (i)
{
x = &x[1];
x.resize(x.size() - 1);
if (AE(x))
return true;
}
else if (x[0] == '-') // (ii)
{
x = &x[1];
if (AE(x))
return true;
}
}
else if (x.find('+') != -1)
{
int firstPlus = x.find('+');
while (firstPlus != -1)
{
string y = &x[firstPlus + 1];
string temp = x;
x.resize(firstPlus);
if (AE(x) && AE(y))
return true;
x = temp;
firstPlus = x.find('+', firstPlus + 1);
}
}
return false;
}

Partial preview of the text

Download Arithmetic Expression and more Assignments Theory of Automata in PDF only on Docsity!

...ructure And Algorithms\Lectures\DSA\01.File_Stream\AE.cpp 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 #include using namespace std; bool isInteger(string x) { if (x.size() == 1 && (x[ 0 ] - '0') >= 0 && (x[ 0 ] - '0') <= 9) return true; return false; } bool AE(string x) { if (isInteger(x)) // Rule 1 : Any number (positive, negative, or zero) return true; else if ((x[ 0 ] == '(' && x[x.size() - 1] == ')') || x[ 0 ] == '-') // Rule 2 { if (x[ 0 ] == '(' && x[x.size() - 1] == ')') // (i) { x = &x[ 1 ]; x.resize(x.size() - 1); if (AE(x)) return true; } else if (x[ 0 ] == '-') // (ii) { x = &x[ 1 ]; if (AE(x)) return true; } } else if (x.find('+') != -1) { int firstPlus = x.find('+'); while (firstPlus != -1) { string y = &x[firstPlus + 1]; string temp = x; x.resize(firstPlus); if (AE(x) && AE(y)) return true; x = temp; firstPlus = x.find('+', firstPlus + 1); } } return false; }