4

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 of it.

Eagle
  • 339
  • 1
  • 3
  • 14

7 Answers7

10
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 don't know how long 'number' is) would 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 still work. Of course, if you printed out x with the usual cout<<x, you would get a confusing answer. But it might serve you at some other time. Of course you would really want to check that number[ii] is between 0 and 9, inclusive - but that's pretty much implied by your question. Still - good programming requires checking, checking, and checking. I'm sure you can add that bit yourself, though.

Floris
  • 45,857
  • 6
  • 70
  • 122
  • 3
    +1 for an awesome basic math solution. Can I double upvote? Elegant! – Nico May 10 '13 at 02:51
  • I would assign sizeof(number) to a variable instead of calculating it every time. – Nico May 10 '13 at 02:54
  • 2
    @nickecarlo - `sizeof` is computed at compile time, so I don't think there's an overhead. See http://stackoverflow.com/questions/2615203/is-sizeof-in-c-evaluated-at-compilation-time-or-run-time – Floris May 10 '13 at 02:56
  • Heh, thanks. I bought my professors habit as good practice without question. – Nico May 10 '13 at 02:58
2

You can think of how to "shift over" a number to the left by multiplying by ten. You can think of appending a digit by adding after a shift.

So you effectively end up with a loop where you do total *= 10 and then total += number[i]

Of course this only works if your array is digits, if it is characters you'll want to do number[i] - '0' and if it is in a different base you'll want to multiply by a different number (8 for instance if it is octal).

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
2
int i = 0, x = 0;
for(; i < arrSize; i++)
    x = x * 10 + number[i];

x is the result.

johnchen902
  • 9,531
  • 1
  • 27
  • 69
2
int i;
int x = 0;
for ( i = 0; i < 4; i++ )
    x = ( 10 * x + number[i] );
unxnut
  • 8,509
  • 3
  • 27
  • 41
2
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;
Ultima
  • 31
  • 5
1

You could 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;
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
Daniel
  • 1,079
  • 1
  • 11
  • 25
1

Answer is quite easy.Just list a complete 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;
}
Bob Cromwell
  • 445
  • 2
  • 14