2011-09-04 32 views
0

只使用如何找到最高溫度,而無需使用移

! ~ &^| + 

我如何才能知道一個32位的數字是TMAX?

TMax是最大二進制補碼數。

我的想法至今都被:

int isTMax(int x) 
{ 
    int y = 0; 

    x = ~x; 
    y = x + x; 

    return !y; 
} 

這僅僅是其中很多事情我都沒有成功嘗試之一,但我只是想不出TMAX的屬性,它會給我回TMAX的。與其他所有整數相比,像將tmax添加到自身將是唯一的。


下面是實際的問題:

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

    x = ~x; 
    y = x + x; 

    return !y; 
} 

int是32位,所以簽訂的最大可能會是0x7FFFFFFF的

+0

什麼是TMAX?最大的無符號(或有符號)整數? – GWW

+2

我想你需要詳細說明什麼是TMax。 – NPE

+0

最大二進制補碼數。對不起,不詳細。 – David

回答

0

也許這樣的事情? 0x7FFFFFFF是最大正符號32位二進制補碼數。

int isTMax(int x){ 
    return !(x^0x7FFFFFFF); 
} 

我不確定,您可能需要將其轉換爲未簽名才能工作。

+0

鑄造是不允許的。 – David

+0

這個作品非常完美,非常感謝你,我不知道爲什麼我試圖去過時。 – David

+0

這個答案可以接受嗎?我假設常量也是不允許的。如果是這樣,那麼是的,這是最好的解決方案。 –

4

據我所知,目前還沒有辦法確定一個特定值是簽署的類型的最大值,而不知道該類型的最大值並進行直接比較。這是因爲簽名的表達式在溢出時遇到未定義的行爲。如果對你的問題有答案,這意味着存在一個在SO上浮動一段時間的嚴重問題的答案:如何以編程方式確定給定簽名類型的最大值。

+0

溢出未處理,所以只有32位將被表示,如果它超過了它的丟失。 – David

+0

不,它調用未定義的行爲,並且不能假定程序輸出的任何內容。誰提出這項任務顯然不知道C ... –

0
#include <stdio.h> 
#include <stdlib.h> 

int test(int n) { 
    return !(n & 0x80000000) & !~(n | (n + 1)); 
} 

// or just effectively do a comparison 

int test2(int n) { 
    return !(n^0x7fffffff); 
} 

int main(int ac, char **av) { 
    printf("is%s TMax\n", test(atoi(av[1])) ? "" : " not"); 
    return 0; 
} 
1
int isTmax(int x) { 


    //add one to x if this is Tmax. If this is Tmax, then this number will become Tmin 
    //uses Tmin = Tmax + 1 
    int plusOne = x + 1; 

    //add to x so desired input becomes 0xFFFFFFFF, which is Umax and also -1 
    //uses Umax = 2Tmax + 1 
    x = x + plusOne; 

    plusOne = !(plusOne); 

    //is x is 0xffffffff, then this becomes zero when ~ is used 
    x = ~x; 
    x = x | plusOne; 
    x = !x; 

    return x; 
} 
相關問題