How to concatenate two integers in C

后端 未结 9 1292
执念已碎
执念已碎 2020-11-29 11:27

Stack Overflow has this question answered in many other languages, but not C. So I thought I\'d ask, since I have the same issue.

How does one concatenate t

9条回答
  •  爱一瞬间的悲伤
    2020-11-29 11:36

    z = x * pow(10, log10(y)+1) + y;
    

    Explanation:

    First you get the number of digits of the variable that should come second:

    int digits = log10(y)+1;  // will be 2 in your example
    

    Then you "shift" the other variable by multiplying it with 10^digits.

    int shifted = x * pow(10, digits);   // will be 1100 in your example
    

    Finally you add the second variable:

    z = shifted + y;   // 1111
    

    Or in one line:

    z = x * pow(10, (int)log10(y)+1) + y;
    

提交回复
热议问题