• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

1.

class Solution {
public:
    int mySqrt(int x) {
        if(x == 0 || x == 1)
            return x;
        int l=1, r=x/2+1, m;
        while(l<=r)
        {
            m = (l+r)>>1;
            long long mul = (long long)m*(long long)m;
            if(mul > x)
                r = m-1;
            else if(mul < x)
                l = m+1;
            else
                return m;
        }
        return r;
    }
};

注意:

long long mul = (long long)m*(long long)m;
这一句中,要先将m转换为long long型,再相乘。

 

2. Newton's Method

// http://en.wikipedia.org/wiki/Newton%27s_method
int sqrt_nt(int x) {
    if (x == 0) return 0;
    double last = 0;
    double res = 1;
    while (res != last)
    {
        last = res;
        res = (res + x / res) / 2;
    }
    return int(res);
}

 

posted on 2016-03-13 15:40  ArgenBarbie  阅读(191)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3