使用 C++ 從陣列中移除前導零
給定一個數組,任務是從給定陣列中移除前導零,然後列印陣列。
Input : arr[] = {0, 0, 0, 1, 2, 3}
Output : 1 2 3
Input : arr[] = {0, 0, 0, 1, 0, 2, 3}
Output : 1 0 2 3在給定的問題中,我們可以建立一個新的陣列,該陣列不包含先前陣列的前導零。
查詢解決方案的方法
在這種方法中,我們將遍歷陣列並插入所有數字,但不包括前導零。
示例
#include <iostream>
using namespace std;
int main() {
int arr[] = {0, 0, 0, 1, 2, 0, 4};
int n = sizeof(arr) / sizeof(int); // size of given array.
int last = -1;
for(int i = 0; i < n; i++) { // finding the first non zero element
if(arr[i] != 0) {
last = i;
break;
}
}
if(last == -1)
cout << "Empty\n";
else {
int b[n - last]; // the new array.
for(int i = last; i < n; i++) // inserting the elements in the new array
b[i-last] = arr[i];
for(int i = 0; i < n-last; i++) // printing the array
cout << b[i] << " ";
}
}輸出
1 2 0 4
以上程式碼的解釋
在給定的程式中,我們首先遍歷陣列 arr 並找到第一個非零元素的索引,將其儲存在名為 last 的變數中。現在,如果在遍歷後 last 為 -1,則意味著我們的整個陣列都由零組成,因此我們列印“空”。
現在,由於我們獲得了第一個非零元素的索引,因此我們可以確定新陣列的大小,即 (n - last),現在我們從 last 迴圈到小於 n。我們將這些元素插入新陣列並列印新陣列。
結論
在本文中,我們解決了一個從陣列中移除前導零的問題。我們還學習了此問題的 C++ 程式以及我們解決的完整方法。我們可以在其他語言(如 C、Java、Python 等)中編寫相同的程式。希望本文對您有所幫助。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP