首页 > 文章列表 > 使用C++从数组中移除前导零

使用C++从数组中移除前导零

数组 移除 前导零
291 2023-08-18

我们提供了一个数组,并且我们的任务是从给定的数组中删除前导零,然后打印该数组。

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 << "Emptyn";
   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和其他语言)编写相同的程序。希望您会觉得本文有帮助。