如何翻转数组中的某些数字
How can I flip certain digits in an array
嘿伙计们,我有一个快速的问题要问你,所以假设我有一个数组,它打印出0000937
.有可能把它变成0000739
吗?如果是这样,我该怎么做?
这个想法是有一个向后计数的计数器,从数组末尾计算第 j 位数字。您将跳过零(实际上将它们放在newArray
中),然后放置最后 j 位数字。
int main()
{
int a[] = {0, 0, 0, 0, 9, 3, 7};
int newArray [(sizeof(a)/sizeof(*a))];
int j = 0;
for(int i=0; i<(sizeof(a)/sizeof(*a)); i++){
if(a[i]==0)
newArray[i]=0; //if the current value is 0, place it as it is
else{
newArray[i]=a[(sizeof(a)/sizeof(*a))-1-j];
j++;
}
}
for(int i=0; i<(sizeof(a)/sizeof(*a)); i++){
cout << a[i];
}
cout << "n";
for(int i=0; i<(sizeof(newArray)/sizeof(*newArray)); i++){
cout << newArray[i];
}
return 0;
}
如果我理解正确,您需要从第一个非 sezo 元素开始反转数组的元素。该任务可以使用标准算法简单地完成。例如
#include <iostream>
#include <algorithm>
#include <iterator>
#include <functional>
int main()
{
int a[] = { 0, 0, 0, 0, 9, 3, 7 };
for ( int x : a ) std::cout << x << ' ';
std::cout << std::endl;
std::reverse(
std::find_if( std::begin( a ), std::end( a ), std::bind2nd( std::not_equal_to<int>(), 0 ) ),
std::end( a ) );
for ( int x : a ) std::cout << x << ' ';
std::cout << std::endl;
}
或者,如果您需要尊重由零元素包围的范围元素,则可以应用相同的方法,但您需要循环来设置非零元素集。我的意思是以下内容
001200045600
结果是
002100065400
只需使用 STD::反向
:标准::反向(arr+4,arr+7);
这会将内容从索引 4(含)反转为索引 7(不包括)。
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 数组/c++中的大量数字
- 遍历并行数组以确定C++中的最大数字
- 整数区间(或 int 数组)中每个数字的出现次数
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 获取 2D 数组 c++ 中的所有数字对
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 以十为基数的数字到布尔数组,该数组要求二进制/基数为 2 的数字
- C++ 检查结果数组中有多少次数字
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 如何在C++中有效地将数字值重新分配给字符数组
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 类、数字/数组或对象中的对象