0

I searched about this but I didn't find a clear answer for this problem in C language.

Imagine that I have an int a = 123 and another int b = 456.

How do I combine them in order to get combine(a, b) == 123456?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Please define the problem more clearly; a single example leaves some questions open. For example, I don't know what `combine(12, 34)`, or `combine(1234, 5678)`, or `combine(5, -3)` should do. – Keith Thompson May 08 '14 at 00:11

3 Answers3

5

You can multiply a by 10-to-the-power-of-N, where N is the number of digits in b, then add that number to b.

Less efficiently, you can convert both to strings, concatenate them, then parse that string into an integer.

In either case, there is a possibility of integer overflow.

If b is allowed to be negative, you will have to further define the desired result.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
1

First find the number of digits in "b" This can be done as follows:

int find_num_digits(int b)
{
 int i = 0;
 while (b > 0)
 {
   b = b/10;
   i++;
 }
return i;
}

Then do: c = a*10^find_num_digits(b) + b;

"c" is the result. You will have to make sure that "c" doesn't go out-of-bounds.

Ravi
  • 31
  • 2
0
int combine(int a, int b) {
  return 1000*a + b;
}

More generically:

int combine(int a, int b) {
  if (b==0) return a;
  return combine(a, b/10)*10+ b%10;
}
sdkljhdf hda
  • 1,387
  • 9
  • 17