-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathHexadecimal Calculation.cpp
More file actions
101 lines (93 loc) · 1.57 KB
/
Hexadecimal Calculation.cpp
File metadata and controls
101 lines (93 loc) · 1.57 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int expression();
int item();
int num();
int multi();
const char * expressionToParse;
char current()
{
return *expressionToParse;
}
char next()
{
return *expressionToParse++;
}
int num()
{
int result = next() - '0';
while (current() >= '0' && current() <= '9')
{
result = 10 * result + next() - '0';
}
return result;
}
int multi()
{
if (current() >= '0' && current() <= '9')
return num();
else if (current() == '(')
{
next();
int result = expression();
next();
return result;
}
return 0;
}
int item()
{
int result = multi();
while (current() == '*')
if (next() == '*')
result *= multi();
return result;
}
int expression()
{
int result = item();
while (current() == '+')
if (next() == '+')
result += item();
return result;
}
int main()
{
string tmp;
while (cin >> tmp) {
char inputArray[110];
string input;
int pos = 0;
int length = 0;
for (int i = 0; i < tmp.length(); i++) {
if (tmp[i] == '+' || tmp[i] == '*' || tmp[i] == '(' || tmp[i] == ')') {
if (length != 0) {
int x;
string t = tmp.substr(pos, length);
stringstream ss;
ss << hex << t;
ss >> x;
input += to_string(x);
}
pos = i + 1;
length = 0;
input += tmp[i];
}
else {
length++;
}
}
if (length != 0) {
input += tmp.substr(pos, length);
}
strcpy(inputArray, input.c_str());
expressionToParse = inputArray;
int result = expression();
cout << hex << uppercase << result << endl;
}
return 0;
}