我在最近的一次采访中被问到这个问题

时间:2015-03-01 11:41:55

标签: c#

我在最近的一次采访中被问到这个问题:

你可以使用数字或数学exprretion而不是布尔短语:

int x = ???;

while(true)
{
    x=???;
    console.write(x + ",");
}
 Output: 9,2,9,2,9,2...

所以这个答案不是很好:

 int x = 2;
 while(true)
 {
     x = x == 2 ? 9:2;
 }

想点什么?

2 个答案:

答案 0 :(得分:4)

使用xor(^)运算符:

int x = 2;

while(true)
{
    x = x ^ 11; // equivalent to x = x ^ 9 ^ 2
    Console.Write(x + ",");
}

由于

9 ^ 11 == 2

2 ^ 11 == 9

另一种方式,作弊:

x = (x / 9) * 2 + 
    (x + unchecked((int)(uint.MaxValue - 8))) / (-7) * 9;

这是基于如何构建int以及如果存在溢出会发生什么。

(x / 9) * 2

如果x == 2,那么x / 9 == 0,所以0 * 2 == 0

如果x == 9,则9/9 == 1,所以1 * 2 == 2

(x + unchecked((int)(uint.MaxValue - 8))) / (-7) * 9

如果x == 2则x + unchecked((int)(uint.MaxValue - 8))== - 7,所以-7 /( - 7)* 9 == 9

如果x == 9,那么x + unchecked((int)(uint.MaxValue - 8))== 0,所以0 /( - 7)* 9 == 0

这两部分相加在一起,所以0 + 9或2 + 0。

或者显然

x = (x + unchecked((int)(uint.MaxValue - 1))) / 7 * 2 +
    (x + unchecked((int)(uint.MaxValue - 8))) / (-7) * 9;

我们两次重复使用“溢出”方法。

一般来说,基于这个原则可能有很多其他的解决方案:你建立一个方程,当x是2时是0,而当x是9时是另一个方程,另一个方程是x,当x是9时是0当x为2时别的东西。然后你将其他东西“标准化”为1(比如我使用的/ 7和/ -7)并将它乘以2和9.可能你可以用SIN或COS构建类似的东西。 / p>

(显然我找不到简单的解决方案......五分钟后我理解使用溢出是没用的......减号运算符直接使用2的整数补码:-))

x = (x - 2) / 7 * 2 +
    (x - 9) / (-7) * 9;

答案 1 :(得分:2)

   int x=2;
   while(true)
   {
    x=11-x;
    console.write(x+",");
   }
相关问题