如何翻转数组中的某些数字

How can I flip certain digits in an array

本文关键字:数字 数组 何翻转 翻转      更新时间:2023-10-16

嘿伙计们,我有一个快速的问题要问你,所以假设我有一个数组,它打印出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(不包括)。