Brainteaser:Bulb Switcher求平方根的思考

前言:

这篇文章的第二种方法是自己实现求平方根,因此我们可以探讨一下,这方面的问题。记得在《数值符号与计算》这门课中,求取平方根的一个方法是牛顿法

引用原文的章节:

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;  
    }  
} 

代码的方法比课中的牛顿法稍微复杂一些。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值