Skip to content

Commit 2c58815

Browse files
committed
Have DigitStore class
Encapsulates both queue and stack, and operations on them used in the main algorithm.
1 parent 6a4ff15 commit 2c58815

File tree

1 file changed

+49
-15
lines changed

1 file changed

+49
-15
lines changed

Diff for: CodeWars/src/UpsideDownNumbers/Solution1.cpp

+49-15
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,53 @@ struct RotationMap
1818
}
1919

2020
};
21-
void storeDigits(int x, std::queue<int>& queue, std::stack<int>& stack)
21+
22+
struct DigitStore
2223
{
23-
int q = x;
24-
do
24+
DigitStore(int x)
2525
{
26-
stack.push(q % 10);
27-
queue.push(q % 10);
28-
q /= 10;
29-
} while (q);
30-
}
26+
int q = x;
27+
do
28+
{
29+
origDigitStore.push(q % 10);
30+
reverseDigitStore.push(q % 10);
31+
q /= 10;
32+
} while (q);
33+
34+
if (std::size(origDigitStore) != std::size(reverseDigitStore))
35+
throw std::logic_error("Both internal digits store are to be the same size");
36+
37+
}
38+
int nextOrigDigit()
39+
{
40+
return origDigitStore.front();
41+
}
42+
43+
int nextReverseDigit()
44+
{
45+
return reverseDigitStore.top();
46+
}
47+
48+
void pop()
49+
{
50+
origDigitStore.pop();
51+
reverseDigitStore.pop();
52+
}
53+
54+
int size()
55+
{
56+
return origDigitStore.size();
57+
}
58+
59+
bool empty()
60+
{
61+
return !size();
62+
}
63+
64+
std::queue<int> origDigitStore;
65+
std::stack<int> reverseDigitStore;
66+
67+
};
3168

3269
bool singleDigit(int x)
3370
{
@@ -48,19 +85,16 @@ int solve(int x, int y)
4885
++x;
4986
continue;
5087
}
51-
std::queue<int> origDigitStore;
52-
std::stack<int> reverseDigitStore;
53-
storeDigits(x, origDigitStore, reverseDigitStore);
88+
DigitStore vDigitStore(x);
5489
auto count{ 0 };
5590
while (true)
5691
{
57-
if (origDigitStore.front() != vRotationMap[reverseDigitStore.top()])
92+
if (vDigitStore.nextOrigDigit() != vRotationMap[vDigitStore.nextReverseDigit()])
5893
break;
5994

6095
++count;
61-
origDigitStore.pop();
62-
reverseDigitStore.pop();
63-
if (!std::size(origDigitStore))
96+
vDigitStore.pop();
97+
if (vDigitStore.empty())
6498
{
6599
++result;
66100
break;

0 commit comments

Comments
 (0)