我们如何在c ++中合并数组的元素?

时间:2015-03-08 11:03:31

标签: c++

我想创建一个合并数组元素的c ++程序例如我们有三个元素是2 5 7,我们想要合并它们使得数字为257

3 个答案:

答案 0 :(得分:1)

最有效的解决方案:

#include <iostream>
using namespace std;
int main()
{
    const int N = 3;
    int a[N] = {2,5,7};

    int num = 0;
    for(int i=0;i<N;i++)
        num = num * 10 + a[i];

    cout << num << endl;
    return 0;
}

步骤进行:

  
      
  1. num - &gt; 0
  2.   
  3. num - &gt; 2
  4.   
  5. num - &gt; 25
  6.   
  7. num - &gt; 257
  8.   

答案 1 :(得分:0)

最简单的方法是使用基于范围的语句。例如

int a[] = { 2, 5, 7 };

int x = 0;

for ( int digit : a ) x = 10 * x + digit;

这是演示程序

#include <iostream>

int main() 
{
    int a[] = { 2, 5, 7 };

    int x = 0;

    for ( int digit : a ) x = 10 * x + digit;

    std::cout << "x = " << x << std::endl;

    return 0;
}

输出

x = 257

使用标题std::accumulate

中声明的标准算法<algorithm>可以完成相同的操作

考虑到数组必须具有可接受的值,如数字,并且结果数不会溢出给定类型累加器的可接受值范围。

答案 2 :(得分:-3)

#include <iostream>
#include <cmath>

int main()
{
    const int N = 3; // the size of the array
    int a[N] = {2,5,7};

    // define the number that will hold our final "merged" number
    int nbr = 0;

    // loop through the array and multiply each number by the correct
    // power of ten and add it to the merged number
    for(int i=N-1;i>=0;--i){
        nbr += a[i] * pow(10, N-1-i);
    }

    // print the number
    std::cout << nbr << std::endl;
    return 0;
}