-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathrotate.cpp
45 lines (36 loc) · 954 Bytes
/
rotate.cpp
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void rotate(vector<int>& nums, int k) {
k = k % nums.size();
reverse(nums.begin(), nums.end() - k);
reverse(nums.end() - k, nums.end());
reverse(nums.begin(), nums.end());
}
int main() {
vector<int> nums;
int n, k;
cout << "Enter the number of elements in the array: ";
cin >> n;
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; ++i) {
int num;
cin >> num;
nums.push_back(num);
}
cout << "Enter the number of positions to rotate to the right: ";
cin >> k;
cout << "Original Array: ";
for (const auto& num : nums) {
cout << num << " ";
}
cout << endl;
rotate(nums, k);
cout << "Array after rotating by " << k << " positions to the right: ";
for (const auto& num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}