Leetcode#69 Sqrt(x)
小心溢出。
检测乘法溢出的方法:设乘数为A、B,乘积为C,检验C / A =? B,前提是B != 0
检测加法溢出的方法:检验A + B <? 0
代码:
1 int sqrt(int x) { 2 int l = 0; 3 int r = x; 4 5 while (l <= r) { 6 int m = l + (r - l) / 2; 7 int p = m * m; 8 bool overflow = m != 0 && p / m != m; 9 if (p == x) 10 return m; 11 else if (!overflow && p < x) 12 l = m + 1; 13 else 14 r = m - 1; 15 } 16 17 return min(l, r); 18 }