How to concatenate two integers in C

后端 未结 9 1264
执念已碎
执念已碎 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:54
    unsigned concatenate(unsigned x, unsigned y) {
        unsigned pow = 10;
        while(y >= pow)
            pow *= 10;
        return x * pow + y;        
    }
    

    Proof of compilation/correctness/speed

    I avoid the log10 and pow functions, because I'm pretty sure they use floating point and are slowish, so this might be faster on your machine. Maybe. Profile.

    0 讨论(0)
  • 2020-11-29 11:55

    here's another way to do it:

    int concat(int x, int y) {
        int temp = y;
        while (y != 0) {
            x *= 10;
            y /= 10;
        }
        return x + temp;
    }
    

    who knows what performance you'll get. just try and see..

    0 讨论(0)
  • 2020-11-29 11:55

    You can also use Macro to concatnate Strings ( Easy way )

    #include<stdio.h>
    #define change(a,b) a##b
    int main()
     {
        int y;
        y=change(12,34);
        printf("%d",y);
        return 0;
     }
    

    It has one Disadvantage. We can't pass arguments in this method

    0 讨论(0)
提交回复
热议问题