C ++使用11个字符的代码交换两个数字 [英] C++ swap two numbers using 11 chars of code

查看:140
本文介绍了C ++使用11个字符的代码交换两个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的朋友给我做了一个他不能做的练习:

(C ++)

My friend sent me a exercise that he can't do:
(C++)

int main()
{
    unsigned int x = 0xB0FF14a5;
    unsigned int y = 0x7340c00e;
    // enter code here
    if(x==0x7340c00e && y==0xB0FF14a5) victory();
    return 0;
}

主要目标是运行 victory / code>函数。

假设:

-max 11个字符

- 您不能使用:main,victory asm,&,*,(,/

-您只能使用一个分号


我尝试使用 #define 和一些其他的东西,但没有什么(我不是C ++高手):/

我不知道如何解决这个问题感谢帮助! / p>

The main goal is to run victory() function.
Assumptions:
-max 11 chars
-You can't use: "main", "victory", "asm", "&", "*", "(", "/"
-You can use only one semicolon

I tried with #define and some other things, but nothing (I'm not C++ master) :/
I have no idea how to solve this; thanks for helping!

推荐答案

使用 XOR交换算法

x^=y^=x^=y;

这与(通常见下文)等同:

This is equivalent (usually, see below) to:

          //x==A,   y==B
x ^= y;   //x==A^B, y==B
y ^= x;   //x==A^B, y==A
x ^= y;   //x==B,   y==A

$ b

在C ++ 03中,单表达式版本是未定义的行为,因此可能无法在所有编译器/平台上正常工作。这是因为在修改和使用变量之间没有序列点。

In C++03 the single-expression version is undefined behavior so may not work correctly on all compilers/platforms. This is because there is no sequence point between modification and use of variables.

在C ++ 11中,它是明确定义的。标准说(5.17.1):

In C++11, it is well-defined. The standard says (5.17.1):


在所有情况下,赋值在右和左操作数的值计算之后排序,并在赋值表达式的值计算之前。

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

这篇关于C ++使用11个字符的代码交换两个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆