简体   繁体   English

检查输入是否为最大的2的补码整数

[英]Check whether the input is the largest 2's complement integer

/*
 * isTmax - returns 1 if x is the maximum, two's complement number,
 *     and 0 otherwise 
 *   Legal ops: ! ~ & ^ | +
 *   Max ops: 10
 *   Rating: 1
 */
int isTmax (int x) 
{
    int t = x + 1;
    return !(t + t) ^ !t;
}  

If x is the largest 2's complement number then 2*t overflows to 0 but its also 0 if x is -1 so we xor it with !t which evaluates to 1. So we must get 1 but somehow the output is 0.如果x是最大的 2 的补数,那么2*t溢出到 0,但如果x是 -1,它也是 0,所以我们用!t对它进行异或,它的计算结果为 1。所以我们必须得到 1 但不知何故输出为 0。

This code is fundamentally wrong.这段代码从根本上是错误的。 Signed overflow is undefined behavior and not guaranteed to give any form of deterministic result.有符号溢出是未定义的行为,不能保证给出任何形式的确定性结果。

To check if a number is the "largest possible", you would rather compare it with INT_MAX from limits.h.要检查一个数字是否“最大”,您宁愿将其与limits.h 中的INT_MAX进行比较。 Or if you will, compare it with (int) ((1u<<31)-1) .或者,如果您愿意,请将其与(int) ((1u<<31)-1)

int isTmax (int x) {
    return !(~(x + x + 1) | !(~x));
}

This works as (x+x+1) becomes -1 if x is INT_MAX and all that's left is to check if x is not -1.如果 x 是 INT_MAX,则 (x+x+1) 变为 -1,剩下的就是检查 x 是否不是 -1。

If constants are allowed, you can do如果允许常量,你可以做

int isTmax (int x) 
{
   return !(((unsigned) x) ^ 0x7fffffff);
}

Otherwise, you can do否则,你可以做

int isTmax (int x) 
{
unsigned nx = ~(unsigned) x;
unsigned r = !(nx + nx) ^ !nx;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM