首頁  >  文章  >  後端開發  >  使用C++從陣列中移除前導零

使用C++從陣列中移除前導零

PHPz
PHPz轉載
2023-09-05 11:13:11825瀏覽

使用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,那麼表示整個陣列都是由零組成,所以我們印出"Empty"。

現在,我們已經得到了第一個非零元素的索引,我們可以確定新數組的大小,即(n - last),然後我們從last開始到n-1運行一個for迴圈。我們將這些元素插入新數組並列印新數組。

結論

在本文中,我們解決了一個問題,即從陣列中刪除前導零。我們也學習了解決這個問題的C 程序和完整的解決方法。我們可以使用其他語言(如C、Java、Python和其他語言)編寫相同的程式。希望您會覺得本文有幫助。

以上是使用C++從陣列中移除前導零的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除