我會輸入向量:{6501,6828,6963,7036,7422,7674,8146,8468,8704,8717,9170 ,9359,9719,9895,9896,9913,9962,154,293,334,492,1323,1479,1539,1727,1870,1943,2383,2392,2996,3282,3812,3903,4465,4605,4665,4772,4828,5142 ,5437,5448,5668,5706,5725,6300,6335};爲什麼操作「>> 1」與C++中的int數據不是「/ 2」
如果我用下面的函數中的代碼計算「Mid」,結果是154,但是當我用「Mid = Left +(Right-Left)>> 1」計算「Mid」時,結果將會是1479. 我不明白髮生了什麼?爲什麼這兩種方式輸出不同的結果?
的功能是:
int minNumberInRotateArray(vector<int> rotateArray) {
if (!rotateArray.size()) return 0;
int Left = 0, Right = rotateArray.size() - 1;
int Mid = Left + (Right - Left)/2;
while (Left < Right)
{
if (rotateArray[Left] < rotateArray[Mid]) Left = Mid;
else if (rotateArray[Right] > rotateArray[Mid]) Right = Mid;
else return rotateArray[Right];
Mid = Left + (Right - Left)/2;
}
return 0;
}
什麼結果是正確的? – xanoetux
你嘗試過Mid = Left +((Right-Left)>> 1)'?恐怕這是運營商優先考慮的問題。 – user0042
你有沒有試過:'(-1 >> 10)'? –