
我们提供了一个数组,并且我们的任务是从给定的数组中删除前导零,然后打印该数组。
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"。
立即学习“C++免费学习笔记(深入)”;
现在,我们已经得到了第一个非零元素的索引,我们可以确定新数组的大小,即(n - last),然后我们从last开始到n-1运行一个for循环。我们将这些元素插入新数组并打印新数组。
在本文中,我们解决了一个问题,即从数组中删除前导零。我们还学习了解决这个问题的C++程序和完整的解决方法。我们可以使用其他语言(如C、Java、Python和其他语言)编写相同的程序。希望您会觉得本文有帮助。
以上就是使用C++从数组中移除前导零的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号