How to convert a vector of multi‑digit numbers to a number in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>

// ------------------------------------------------------------
// ArrayToNumber
// Converts a vector<int> into a single integer by concatenating
// each element as a string. Works for multi-digit numbers.
// Example: {14, 6, 9, 31, 20} ->14693120
// ------------------------------------------------------------
int ArrayToNumber(const std::vector<int>& arr) {
    std::string s = "";

    for (int num : arr) {
        s += std::to_string(num);   // concatenate as text
    }

    return std::stoi(s);            // convert final string to int
}

int main()
{
    std::vector<int> arr = { 14, 6, 9, 31, 20 };

    int n = ArrayToNumber(arr);

    std::cout << "n = " << n << std::endl;
}


/*
run:

n = 14693120

*/

 



answered May 11 by avibootz
...