8. Sqrt(x)

Link to the problem

Description

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example

Input: 4, Output: 2
Input: 8, Output: 2

Idea

Use Newton's iteration.
Let f(x) = x^2 - n. To solve for f(x) = 0. Start from some initial x_0, and update as x_{i + 1} = x_i - f(x_i)/f'(x_i) = x_i - (x_i^2 - n)/(2x_i) = (x_i + n/x_i)/2.

Solution

class Solution {
public:
    int mySqrt(int x) {
        if (!x) return 0;
        long rtn = x;
        while (rtn * rtn > x) {
            if ((rtn - 1) * (rtn - 1) <= x) return (int) rtn - 1;
            rtn = (rtn + x / rtn) / 2;
        }
        return (int) rtn;
    }
};

1017 / 1017 test cases passed.
Runtime: 15 ms

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,752评论 0 38
  • 早上赖床,摁掉几个闹钟才能爬得起来,完全不知道怎么醒,去到公司就犯困; 兴致勃勃地拿起一本书,翻开没几页,发现自己...
    徐徐而闻阅读 3,971评论 0 1
  • 2014.11.30 已是很久没有再写日记,每次写时都感觉时光都被偷走了,明明是每一刻都充实得有些厚重,却无...
    何步阅读 1,445评论 0 0
  • 我不喜欢吃南京的皮肚面,皮肚面就像大杂烩。我喜欢吃湖州的浇头面,浓汤,软硬恰当的面条,加上各种各样的浇头,最有特色...
    吴兴老鱼阅读 2,976评论 0 0

友情链接更多精彩内容