João Filipe
João Filipe

Reputation: 5

How to combine 2 integers in order to get 1?

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?

Upvotes: 0

Views: 1063

Answers (3)

sdkljhdf hda
sdkljhdf hda

Reputation: 1407

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;
}

Upvotes: 0

Ravi
Ravi

Reputation: 31

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.

Upvotes: 1

Eric J.
Eric J.

Reputation: 150148

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.

Upvotes: 5

Related Questions