C++ 程序把第一个元素翻倍并移动到末尾
在本教程中,我们将编写一个程序,将第一个元素翻倍,并将所有零移动到给定数组的末尾。
当相邻索引中有两个相同的元素时,我们必须将一个数翻倍。之后,我们必须向数组添加一个零。
将数组中的所有零移动到末尾。
示例
让我们看看代码。
#include <bits/stdc++.h>
using namespace std;
void moveZeroesToEnd(int arr[], int n) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
arr[count++] = arr[i];
}
}
while (count < n) {
arr[count++] = 0;
}
}
void updateAndRearrangeArray(int arr[], int n) {
if (n == 1) {
return;
}
for (int i = 0; i < n - 1; i++) {
if ((arr[i] != 0) && (arr[i] == arr[i + 1])) {
arr[i] = 2 * arr[i];
arr[i + 1] = 0;
i++;
}
}
moveZeroesToEnd(arr, n);
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
int main() {
int arr[] = { 2, 3, 3, 4, 0, 5, 5, 0 }, n = 7;
cout << "Given Array: ";
printArray(arr, n);
cout << endl;
updateAndRearrangeArray(arr, n);
cout << "Updated Array: ";
printArray(arr, n);
cout << endl;
return 0;
}输出
如果你执行上述程序,你将获得以下结果。
Given Array: 2 3 3 4 0 5 5 Updated Array: 2 6 4 10 0 0 0
结论
如果你对本教程有任何疑问,请在评论区提及。
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP