用C进行按位运算以比较两个整数 [英] Bitwise operation in C to compare two integers
问题描述
我最近在一个班上接受了测验.问题如下:
I was recently given a quiz in one of my classes. The question is below:
在C语言中编写一个函数(称为
cmp
),该函数接受两个整数(x
和y
) 并返回:-1
如果x
<y
,如果x
=y
,则为0
,如果x
>y
,则为1
.尽可能简洁地写cmp
.
Write a function (called
cmp
) in C that accepts two integers (x
andy
) and returns:-1
ifx
<y
,0
ifx
=y
,1
ifx
>y
. Writecmp
as concise as possible.
我能想到的最简洁的功能是:
The most concise function that I could think of was:
int cmp(int x, int y) {
return ((x < y) ? (-1) : ((x == y) ? (0) : (1)));
}
但是我感觉可能会有一些操纵,我可以使用它来更简洁地做到这一点.也许&
和^
的组合?在过去的几天里,这一直困扰着我,我想知道实际上是否有 IS 做到这一点的更好方法?
But I have a feeling there could be a bit manipulation that I could use to do this more concisely. Perhaps a combination of &
and ^
? This has been bothering me for the last few days and I wanted to know if there in fact IS a better way to do this?
推荐答案
尽可能简洁"是对测验的一个非常模糊的要求.您是否希望打高尔夫球?是否删除空格和括号使其更简洁?无论如何,这是一种对比较结果进行算术运算的解决方案:
"as concise as possible" is an extremely vague requirement for a quiz. Are you expected to do code golf? Does removing whitespace and parentheses make it more concise? Anyway, here’s one solution using arithmetic on the results of comparisons:
int cmp(int x, int y) {
return (x > y) - (x < y);
}
这篇关于用C进行按位运算以比较两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!