前言:
这篇文章的第二种方法是自己实现求平方根,因此我们可以探讨一下,这方面的问题。记得在《数值符号与计算》这门课中,求取平方根的一个方法是牛顿法。
引用原文的章节:
if we try to find another way to compute the result (actually it is Integer Square Root of n ), we will find many methods. One of them is below credited to this stackoverflow question.
public class Solution { public int bulbSwitch(int n) { return isqrt(n); } public int isqrt(int n){ int op = n; int res = 0; int one = 1 << 30; // The second-to-top bit is set: use 1u << 14 for uint16_t type; use 1uL<<30 for uint32_t type // "one" starts at the highest power of four <= than the argument. while (one > op) { one >>= 2; } while (one != 0) { if (op >= res + one) { op = op - (res + one); res = res + 2 * one; } res >>= 1; one >>= 2; } return res; } }
代码的方法比课中的牛顿法稍微复杂一些。