我必须实现一个函数,得到两个数字之一:4或7。该函数必须返回第二个数字,而不使用算术运算,例如:
如果函数得到4作为参数,它返回7,
如果函数得到7作为参数,它返回4。
我寻找一个解决方案,而不是明显的return x==7?4:7
有可能解决了这些数字的二进制表示属性
由于4是二进制的100
, 7是111
,您只需将输入与3 (11
)异或。
这样,100 xor 011 = 111
和111 xor 011 == 100
。
这有点不够明确,如果我们传递的是(比如)11,12或4711,我们应该返回什么?下面的函数返回4和7的预期结果,但对于任何非指定的情况返回-1。
/* Returns 4, if passed 7, 7 if passed 4.
* If passed a number not 4 or 7, returns -1
*/
int f(int x)
{
switch (x) {
case 4: return 7;
case 7: return 4;
default: return -1;
}
算术:
int f(int x){
return 11-x;
}
使用地图:Map<int, int> dictionary = new HashMap();
dictionary.put(4,7);
dictionary.put(7,4);
int f(int x){
return dictionary.get(x);
}