soulmachine / leetcode

LeetCode题解,151道题完整版。
BSD 3-Clause "New" or "Revised" License
11.27k stars 3.43k forks source link

the sum of two integer may overflow. #37

Closed advancedxy closed 9 years ago

advancedxy commented 9 years ago

see http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html for details.

soulmachine commented 9 years ago

你的这个改动很好,不过本书的代码,更加注重可读性。

如果连简单的 x+y 都要考虑溢出,那代码会变得非常难懂

advancedxy commented 9 years ago
  1. 这是个 bug, 一旦数组的大小超过2^30接近2^31-1, 搜索数组后半截的数肯定会失败.
  2. 对于 x + y 取平均数而言, 这个改动可读性并没有降低. 实际上, 任何强类型的语言在做类似的取平均数的时候都应该使用上面的做法.
  3. 本书其他地方取平均数的代码就是使用我改动后的代码, 我当时用 grep 过了一遍.
soulmachine commented 9 years ago

我重新grep了一把,发现以前的确有很多防止溢出的写法,那这个也采纳吧,非常感谢!