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).
sum = num1 + num2; After that it is displayed on screen using the cout object.
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.
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;
}
You could convert them into strings, combine them and then convert them back to an int?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With