如何在不使用临时变量或算术运算的情况下交换两个数字?

发布于 2024-09-17 06:10:37 字数 116 浏览 18 评论 0原文

该方程在没有临时变量的情况下交换两个数字,但使用算术运算:

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

如何在没有算术运算的情况下做到这一点?我在考虑异或。

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

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

How can I do it without arithmetic operations? I was thinking about XOR.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

夜清冷一曲。 2024-09-24 06:10:37
a=a+b;
b=a-b;
a=a-b;

这很简单但有效......

a=a+b;
b=a-b;
a=a-b;

This is simple yet effective....

策马西风 2024-09-24 06:10:37

为什么不使用标准库?

std::swap(a,b);

Why not use the std libs?

std::swap(a,b);
笑忘罢 2024-09-24 06:10:37

在 C 中,这应该可以工作:

a = a^b;
b = a^b;
a = a^b;

或者更酷/更极客的外观:

a^=b;
b^=a;
a^=b;

有关更多详细信息,请查看 this。 XOR 是一个非常强大的运算,到处都会出现许多有趣的用法。

In C this should work:

a = a^b;
b = a^b;
a = a^b;

OR a cooler/geekier looking:

a^=b;
b^=a;
a^=b;

For more details look into this. XOR is a very powerful operation that has many interesting usages cropping up here and there.

春花秋月 2024-09-24 06:10:37

在不使用任何临时存储或算术运算的情况下交换两个数字的最佳方法是将两个变量加载到寄存器中,然后以相反的方式使用寄存器!

你不能直接从 C 语言中做到这一点,但编译器可能很有能力为你解决这个问题(至少,如果启用了优化) - 如果你编写简单、明显的代码,例如 KennyTM 在他的评论中建议的代码。

例如,

void swap_tmp(unsigned int *p)
{
  unsigned int tmp;

  tmp = p[0];
  p[0] = p[1];
  p[1] = tmp;
}

使用带有 -O2 优化标志的 gcc 4.3.2 编译给出:

swap_tmp:
        pushl   %ebp               ;  (prologue)
        movl    %esp, %ebp         ;  (prologue)
        movl    8(%ebp), %eax      ; EAX = p
        movl    (%eax), %ecx       ; ECX = p[0]
        movl    4(%eax), %edx      ; EDX = p[1]
        movl    %ecx, 4(%eax)      ; p[1] = ECX
        movl    %edx, (%eax)       ; p[0] = EDX
        popl    %ebp               ;  (epilogue)
        ret                        ;  (epilogue)

The best way to swap two numbers without using any temporary storage or arithmetic operations is to load both variables into registers, and then use the registers the other way around!

You can't do that directly from C, but the compiler is probably quite capable of working it out for you (at least, if optimisation is enabled) - if you write simple, obvious code, such as that which KennyTM suggested in his comment.

e.g.

void swap_tmp(unsigned int *p)
{
  unsigned int tmp;

  tmp = p[0];
  p[0] = p[1];
  p[1] = tmp;
}

compiled with gcc 4.3.2 with the -O2 optimisation flag gives:

swap_tmp:
        pushl   %ebp               ;  (prologue)
        movl    %esp, %ebp         ;  (prologue)
        movl    8(%ebp), %eax      ; EAX = p
        movl    (%eax), %ecx       ; ECX = p[0]
        movl    4(%eax), %edx      ; EDX = p[1]
        movl    %ecx, 4(%eax)      ; p[1] = ECX
        movl    %edx, (%eax)       ; p[0] = EDX
        popl    %ebp               ;  (epilogue)
        ret                        ;  (epilogue)
避讳 2024-09-24 06:10:37

我以前没有见过这个 C 解决方案,但我确信有人已经想到过它。也许比我有更多的发帖自控能力。

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

没有额外的变量!

它对我有用,但根据 stdio 实现,您可能需要对输出缓冲进行一些操作。

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.

时间海 2024-09-24 06:10:37

使用 XOR,

void swap(int &a, int &b)
{
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
}

带有 XOR 的一个衬垫,

void swap(int &a, int &b)
{
    a ^= b ^= a ^= b;
}

这些方法看起来很干净,因为它们对于任何测试用例都不会失败,但同样,因为(如方法 2 中)变量的值在同一序列点内被修改两次,所以据说具有 ANSI C 声明的未定义行为。

Using XOR,

void swap(int &a, int &b)
{
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
}

One liner with XOR,

void swap(int &a, int &b)
{
    a ^= b ^= a ^= b;
}

These methods appear to be clean, because they don't fail for any test-case, but again since (as in method 2) value of variable is modified twice within the same sequence point, it is said to be having undefined behavior declared by ANSI C.

若水般的淡然安静女子 2024-09-24 06:10:37

C++11 允许:

C++11 allows to:

  • Swap values:

    std::swap(a, b);
    
  • Swap ranges:

    std::swap_ranges(a.begin(), a.end(), b.begin());
    
  • Create LValue tuple with tie:

    std::tie(b, a) = std::make_tuple(a, b);
    
    std::tie(c, b, a) = std::make_tuple(a, b, c);
    
蓝咒 2024-09-24 06:10:37
a =((a = a + b) - (b = a - b));
a =((a = a + b) - (b = a - b));
深海少女心 2024-09-24 06:10:37

除了上述针对其中一个值超出有符号整数范围的情况的解决方案之外,还可以通过这种方式交换两个变量值

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

In addition to the above solutions for a case where if one of the value is out of range for a signed integer, the two variables values can be swapped in this way

a = a+b;
b=b-(-a);
a=b-a;
b=-(b);
节枝 2024-09-24 06:10:37

也可以使用乘法和除法。

 int x = 10, y = 5;

 // Code to swap 'x' and 'y'
 x = x * y;  // x now becomes 50
 y = x / y;  // y becomes 10
 x = x / y;  // x becomes 5

Multiplication and division can also be used.

 int x = 10, y = 5;

 // Code to swap 'x' and 'y'
 x = x * y;  // x now becomes 50
 y = x / y;  // y becomes 10
 x = x / y;  // x becomes 5
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文