-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem58.cpp
More file actions
84 lines (67 loc) · 1.69 KB
/
problem58.cpp
File metadata and controls
84 lines (67 loc) · 1.69 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
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
class InputHandler {
public:
int n;
int* nums;
InputHandler() : n(0), nums(nullptr) {}
void getInput() {
cout << "Enter the magical stones numbers in non-decreasing order: ";
string line;
getline(cin, line);
stringstream ss(line);
vector<int> temp;
int num;
while (ss >> num) {
temp.push_back(num);
}
n = temp.size();
nums = new int[n];
for (int i = 0; i < n; ++i) {
nums[i] = temp[i];
}
}
~InputHandler() {
delete[] nums;
}
};
class MagicalTransformer {
public:
static int* transformAndSort(int* nums, int n) {
int* result = new int[n];
int left = 0, right = n - 1;
int pos = n - 1;
while (left <= right) {
int leftSq = nums[left] * nums[left];
int rightSq = nums[right] * nums[right];
if (leftSq > rightSq) {
result[pos--] = leftSq;
++left;
} else {
result[pos--] = rightSq;
--right;
}
}
return result;
}
};
class OutputHandler {
public:
static void printArray(int* arr, int n) {
cout << "The transformed magical numbers: ";
for (int i = 0; i < n; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
};
int main() {
InputHandler input;
input.getInput();
int* squaredSorted = MagicalTransformer::transformAndSort(input.nums, input.n);
OutputHandler::printArray(squaredSorted, input.n);
delete[] squaredSorted;
return 0;
}