Combine two numbers into one. Example: 123 and 456 become 123456
Solution 1
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;
}
Solution 2
You could convert them into strings, combine them and then convert them back to an int?
Solution 3
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...
Solution 4
For each digit in int2
, you can multiple int1
by 10 and then add int2
:
// merge(123, 0) => 1230
int merge(int int1, int int2)
{
int int2_copy = int2;
do
{
int1 *= 10;
int2_copy /= 10;
} while (int2_copy);
return int1 + int2;
}
You could get rid of the loop using log10
and ceil
.
Solution 5
Assuming both ints are non-negative, and int1 goes on the left and int2 goes on the right, you need to figure out how many digits long int2 is, multiply int1 by 10 a bunch of times, and then add them.
unsigned int int1 = blah;
unsigned int int2 = blah;
unsigned int temp = int2;
do
{
temp /= 10;
int1 *= 10;
} while (temp >0)
unsigned int newInt = int1 + int2;
bei
Updated on July 09, 2022Comments
-
bei almost 2 years
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).