Home > Software engineering >  How to convert a list of multiple integers into a single integer in c ?
How to convert a list of multiple integers into a single integer in c ?

Time:01-15

How do I convert a list in c such as: int nums = [1,2,3]; to an integer (int) of 123 ?

I tried evrey thing i can. can someone Please help me

CodePudding user response:

You could iterate over the list and in each iteration multiply the sum so far by 10 and add the current element:

list<int> nums = {1, 2, 3};
int result = 0;
for (list<int>::const_iterator it = nums.begin(); it != nums.end();   it) {
    result = result * 10   (*it);
}

CodePudding user response:

Assuming your list is

int nums[] = {1,2,3}

your final number will be (3 2x10 3x100), so it is just a matter of coding it properly. You could do so with the following lines, after adding the math standard headers (#include <math.h>)

int final_number = 0;
int size = sizeof(nums)/sizeof(int);
for(int i = 0; i < size;   i) 
    final_number  = nums[i]*pow(10, i);

CodePudding user response:

This should do what you want:

# include <iostream>

using namespace std;

int main()
{
    int arr[] = {12,2,3};
    int size = sizeof(arr) / sizeof(arr[0]);

    int result = 0;
    for (int i = 0; i < size; i  )
    {
        result = result * 10   arr[i];
    }
    cout << result;

    return 0;
}
  • Related