Fast sign of integer in C

前端 未结 5 1099
轮回少年
轮回少年 2020-12-06 11:57

There is a sign function in C:

int sign(int x)
{
    if(x > 0) return 1;
    if(x < 0) return -1;
    return 0;
}

Unfortunately, comp

5条回答
  •  执念已碎
    2020-12-06 12:25

    If s(x) is a function that returns the sign-bit of x (you implemented it by ((unsigned int)x)>>31), you can combine s(x) and s(-x) in some way. Here is a "truth table":

    x > 0: s(x) = 0; s(-x) = 1; your function must return 1

    x < 0: s(x) = 1; s(-x) = 0; your function must return -1

    x = 0: s(x) = 0; s(-x) = 0; your function must return 0

    So you can combine them in the following way:

    s(-x) - s(x)
    

提交回复
热议问题