How to swap two numbers without using temp variables or arithmetic operations?

后端 未结 10 1004
Happy的楠姐
Happy的楠姐 2020-12-13 00:09

This equation swaps two numbers without a temporary variable, but uses arithmetic operations:

a = (a+b) - (b=a);

How can I do it without ar

10条回答
  •  抹茶落季
    2020-12-13 00:47

    I haven't seen this C solution before, but I'm sure someone has thought of it. And perhaps had more posting self-control than I do.

    fprintf(fopen("temp.txt", "w"), "%d", a);
    a = b;
    fscanf(fopen("temp.txt", "r"), "%d", &b);
    

    No extra variables!

    It works for me, but depending on the stdio implementation you may have to do something about output buffering.

提交回复
热议问题