2012-04-14 65 views
2

我需要在C中使用按位運算創建一個方法,檢查x + y是否會溢出。我最多隻能使用以下操作中的20個; ! 〜&^| + < < >>請記住,我必須測試負數和正數。創建方法,檢查x + y是否會使用按位運算溢出

我試了幾次才使它工作。我的邏輯聲音是?我要: 如果(x + y)小於x,則溢出。基於這個邏輯,我寫了這個;

int addOK(int x, int y) 
{ 
    int sum = x + y; 
    int nx = ((~x) + 1); 
    int check = (sum + nx)>>31; 
    return !check; 
} 

謝謝!

+0

不幸的是,有符號整數溢出導致未定義的行爲。因此,在你的函數中,你無法控制'sum'中存儲的內容,所以你的支票並沒有很好的定義。 – 2012-04-14 16:15:38

+0

@guambler ...如果添加「-128」和「127」會發生什麼?當然是'8位',我猜你的邏輯會失敗。任何方式來解決這個問題? – noufal 2013-05-29 10:20:51

回答

0

這應該工作,但它不會只使用位運算符,但它的簽署工作:

int addOK(int x, int y) 
{ 
    int check; 
    if (greaterThan(0, x^y)) 
    check = 0; 
    else if (greaterThan(x, 0)) 
    check = greaterThan(y, INT_MAX -x); 
    else 
    check = greaterThan(INT_MIN -x, y); 

    return check; 
} 

int greaterThan(int first, int second) { 
    /* first > second means second - first is less than 0 
     shift the sign bit and then compare it to 1 */ 
    return (second + (~first +1)) >> ((sizeof(int) * 8) -1) & 1; 
} 

如果這兩個數字均爲正應該足夠:

int addOK(int x, int y) { 
if(x^y < 0) 
    return 0; 

return 1; 
} 
+0

,看起來像聲音邏輯,我會盡量將其轉換爲按位 – Guambler 2012-04-14 16:22:11

+0

看看我更新的答案,現在它以更按位的方式實現... – aleroot 2012-04-14 16:28:51