Convert int array to int value in c

I have an integer array

int number[] = {1,2,3,4}; 

What can I do to get int x = 1234? I need to have a c version.

+4
source share
7 answers
 x = 1000*number[0] + 100*number[1] + 10*number[2] + number[3]; 

This is basically how decimal numbers work. A more general version (when you do not know how long the "number") will be:

 int x = 0; int base = 10; for(int ii = 0; ii < sizeof(number); ii++) x = base*x + number[ii]; 

Note. If base is something other than 10, the above code will work. Of course, if you typed x using the usual cout<<x , you get a confused answer. But it may serve you another time. Of course, you really want to check that number[ii] is between 0 and 9 inclusive, but this is pretty much implied by your question. However, good programming requires verification, verification, and verification. I am sure you can add this bit yourself.

+10
source

You might think about how to β€œshift” the number to the left by multiplying by ten. You can come up with adding numbers by adding after the shift.

So, you will actually end the loop in which you do total *= 10 , and then total += number[i]

Of course, this only works if your array is numbers, if it is the characters you want to make number[i] - '0' , and if it is in a different base, you will want to multiply by another number (for example, if it is octal).

+2
source
 int i = 0, x = 0; for(; i < arrSize; i++) x = x * 10 + number[i]; 

x is the result.

+2
source
 int i; int x = 0; for ( i = 0; i < 4; i++ ) x = ( 10 * x + number[i] ); 
+2
source
 int number[]={1,2,3,4} int x=0,temp; temp=10; for(i=0;i<number.length;i++) { x=x*temp+number[i]; } cout>>x; 
+2
source

You can do something with a for loop and powers of 10

 int tens = 1; int final = 0; for (int i = arrSize - 1; i <= 0; ++i) { final += tens*number[i]; tens*=10; } return final; 
+1
source

The answer is pretty simple. Just specify the full function here.

 int toNumber(int number[],arraySize) { int i; int value = 0; for(i = 0;i < arraySize;i++) { value *=10; value += number[i]; } return value; } 
+1
source

Source: https://habr.com/ru/post/1480030/


All Articles