Concatenate numbers in a vector to form one number

1.8k views Asked by At

I have a function which feeds a vector series of numbers. This series of numbers is to be appended to form a long long number and get stored in another vector.

Eg.

Vector1= |2|3|4|5|5|
vector2= |23455|     |

A space indicates the end of one number and functions starts to output second number series. I think reverse iterator and multiply by 10^x is somehow a solution.

Eg code

vector<long long> a, fin;
for (int i = 0; i <6; i++)
{
    a.push_back(i + 1);    //  adds 1 2 3 4 5 6  in slots of v1


}
int j = 0;
for (vector<long long>::reverse_iterator i = a.rbegin(); i != a.rend(); i++)  { 
// want to append v1 members to form one number 123456 and store it in first slot of vector2;

    fin[0] += (a[(*i)] * (10 ^ j)); 
    j++;
}
cout << fin[0];
2

There are 2 answers

1
Galik On BEST ANSWER

You didn't put any elements in your fin vector. Also you mistook ^ for power function. You need to use std::pow:

Try:

#include <cmath>
#include <vector>
#include <iostream>

using namespace std;

int main ()
{
    vector<long long> a;
    vector<long long> fin(1); // add an element

    for (int i = 0; i <6; i++)
    {
        a.push_back(i + 1);
    }

    int j = 0;
    for (vector<long long>::reverse_iterator i = a.rbegin(); i != a.rend(); i++) {
//      fin[0] += (a[(*i)] * (10 ^ j)); // ??
        fin[0] += ((*i) * pow(10, j)); // not ^
        j++;
    }
    cout << fin[0];
}

Output:

123456
0
Benjamin Lindley On

The simplest way to do this is probably to use a stringstream to convert the numbers to a string, then convert the string back to a number.

std::vector<long long> input = { 1, 2, 3, 4, 5 };
std::ostringstream oss;
for (auto i : input)
    oss << i;
long long output = std::stoll(oss.str());

A more efficient way to do this, assuming you only have single digit numbers, would be as follows:

long long output = 0;
for (auto i : input)
    output = output * 10 + i;