You can concatenate numbers of type int

5

For example 10 and 12, concatenated would be 1012, this would not be string , it would have to be integer type, can you do that?

    
asked by anonymous 08.02.2018 / 16:07

2 answers

7

It has, but the algorithm that works in all cases would be complex, it almost always makes up for using the string to do the concatenation.

So if you're expecting an instruction or a function ready in the language that delivers the result, you do not.

The mathematical basis that you must use to build the algorithm is to multiply the first number by 10 to the number of digits of it, in example 10 it has 2 digits, so it must multiply by 100, it only adds to the second. p>

In any numerical basis each digit on the left has a greater weight in geometric progression according to its. So whenever you want to put digits to the left you should raise the base (in case 10 since we deal with decimal) with the digit position then 1234 + 123 + 12 You navigate like this:

1 x 10 8 + 2 x 10 7 + 3 x 10 6 + 4 x 10 5 + 1 x 10 4 + 2 x 10 3 + 3 x 10 2 + 1 x 10 1 + 2 x 10 0

1 x 100,000,000 + 2 x 10,000,000 + 3 x 1,000,000 + 4 x 100,000 + 1 x 10,000 + 2 x 1,000 + 3 x 100 + 1 x 10 + 1 x 2

100,000,000 + 20,000,000 + 3,000,000 + 400,000 + 10,000 + 2,000 + 300 + 10 + 2

123.412.312

Obviously you have to do the reverse process to break the number into digits.

If you have any specific programming questions while you are doing this, you can ask a specific question.

    
08.02.2018 / 16:14
3

For a general solution, see @Maniero's answer. If you really need it, it compensates for a specific function of yours.

for output in int, see at the end of the answer

Generating a string :

If it's for fast stuff, such as a debug , or just an output format, C has an alternative that is the printf family and its sprintf / p>

Example

Playing in stdout :

printf("%02d%02d\n", v1, v2);

See working at IDEONE .


To write to a buffer:

sprintf( destino, "%02d%02d", v1, v2);


Basically these functions get a string that will be interpolated, and the parameters to be interpolated. In our case:

┌──── % marca a posição onde entrará um valor interpolado
│┌─── significa "preencher com zero a esquerda
││┌── indica que o preenchimento deve ter 2 casas
│││┌─ indica que o valor interpolado será tratado como decimal
%02d

Here's more interesting information:

  

What are the differences between printf, fprintf, sprintf, snprintf, printf_s, and fprintf_s?

Generating an int :

If you need numerical values, the concatenation is mathematical:

concatenado = valor1 * 100 + valor2;

Or, limiting to two boxes by dropping overflow :

concatenado = ( valor1 % 100 ) * 100 + ( valor2 % 100 )

(which is what is already in @Maniero's response, I only applied to your case).

    
27.04.2018 / 19:12