Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two numbers into one. Example: 123 and 456 become 123456

In C++, how do I combine (note: not add) two integers into one big integer?

For example:

int1 = 123;
int2 = 456;

Is there a function to take the two numbers and turn intCombined into 123456?

EDIT:

My bad for not explaining clearly. If int2 is 0, then the answer should be 123, not 1230. In actuality though, int1 (the number on the left side) would only have a value if int2 goes over the 32 bit limit. So when int2 is 0, then int1 is 0 (or garbage, i'm not sure).

like image 906
bei Avatar asked Apr 09 '10 21:04

bei


People also ask

How do you put 2 numbers together in C++?

sum = num1 + num2; After that it is displayed on screen using the cout object.

How to merge two variables in c?

here is a less confusing way char combine[100]; int a = 123; int b = 456; int c; sprintf(combine, "%d%d", a, b); sscanf(combine, "%d", &c); printf("%d", c); >>> 123456 try to learn about sscanf and sprintf, it'll come in handy for you a lot of times.


3 Answers

The power of ten, that you need to multiply the first number with, is the smallest one, that is bigger than the second number:

int combine(int a, int b) {
   int times = 1;
   while (times <= b)
      times *= 10;
   return a*times + b;
} 
like image 66
sth Avatar answered Oct 19 '22 20:10

sth


You could convert them into strings, combine them and then convert them back to an int?

like image 38
Jan Johansen Avatar answered Oct 19 '22 21:10

Jan Johansen


If the numbers you are trying to combine are positive integers you can use pairing Functions.

Pairing function creates a unique number from two. It is also a reversible function.

x,y -> z
z -> x,y

z = (x+y)(x+y+1)/2 + y

Then the reverse is:

w = floor((sqrt(8z+1)-1)/2)
t = (w*w + w)/2
y = z - t
x = w - y

Note. The above is not in any specific language. Just some math...

like image 9
Noel Avatar answered Oct 19 '22 19:10

Noel