题目

Total Accepted: 67411 Total Submissions: 286086 Difficulty: Medium

Implement int sqrt(int x).

Compute and return the square root of x.

分析

不适用库函数实现求根。

该题目一种解法是利用二分的思想,要注意的问题便是计算溢出问题,数据类型应该采用unsigned long long ;

另一种解法是 牛顿迭代法,思想参考百度百科 以及参考博客

为了方便理解,就先以本题为例:



计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如左图所示。

首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交点为x1。

同样的道理,如果x1不是解,做一个经过(x1,f(x1))这个点的切线,与x轴的交点为x2。

以此类推。

以这样的方式得到的xi会无限趋近于f(x)=0的解。

判断xi是否是f(x)=0的解有两种方法:

一是直接计算f(xi)的值判断是否为0,二是判断前后两个解xi和xi-1是否无限接近。

经过(xi, f(xi))这个点的切线方程为f(x) = f(xi) + f’(xi)(x - xi),其中f’(x)为f(x)的导数,本题中为2x。令切线方程等于0,即可求出xi+1=xi - f(xi) / f’(xi)。

继续化简,xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2。

AC代码

class Solution {
public:
int mySqrt(int x) {
if (x < 0)
return -1; //使用二分法求解
unsigned long long lhs = 0, rhs = (x + 1) / 2; while (lhs <= rhs)
{
unsigned long long mid = (lhs + rhs) / 2;
//注意溢出问题,使用无符号长整型存储临时乘积
unsigned long long tmp1 = mid * mid;
if (tmp1 == x)
{
return mid;
}
else if (tmp1 < x)
{
lhs = mid + 1;
}
else{
rhs = mid - 1;
}//else
}//while unsigned long long tmp = lhs * lhs;
if (tmp <= x)
return lhs;
else
return rhs;
}
};

GitHub测试程序源码

LeetCode(69) Sqrt(x)的更多相关文章

  1. LeetCode(69):x 的平方根

    Easy! 题目描述: 实现 int sqrt(int x) 函数. 计算并返回 x 的平方根,其中 x 是非负整数. 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去. 示例 1: 输入: ...

  2. Qt 学习之路 2(69):进程

    Qt 学习之路 2(69):进程 豆子 2013年11月9日 Qt 学习之路 2 15条评论 进程是操作系统的基础之一.一个进程可以认为是一个正在执行的程序.我们可以把进程当做计算机运行时的一个基础单 ...

  3. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  4. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  5. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  6. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  7. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  8. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

  9. LeetCode(107) Binary Tree Level Order Traversal II

    题目 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from l ...

随机推荐

  1. Django models数据库配置以及多数据库调用设置

    今天来说说web框架Django怎么配置使用数据库,也就是传说中MVC(Model View Controller)中的M,Model(模型). 简单介绍一下Django中的MVC: 模型(model ...

  2. 关于C_Cpp的一些小结

    ## 某些函数的使用 1. printf / sprintf / fprintf printf:把格式字符串输出到标准输出(可重定向) sprintf:把格式字符串输出到指定字符串中,参数比print ...

  3. python之list操作

    序列是Python中最基本的数据结构.序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推. 列表(list)是最常用的Python数据类型,它可以作为一个方 ...

  4. Kruskal && Prim模板

    1. Kruskal(并查集模板): /* Kruskal:并查集实现,记录两点和距离,按距离升序排序,O (ElogE) */ struct Edge { int u, v, w; bool ope ...

  5. Squid启动报:Could not determine this machines public hostname. Please configure one or set 'visible_hostname'.

    在squid.conf中添加 visible_hostname squid.packet-pushers.net 或者编辑/etc/hosts文件, 在该文件中制定主机IP地址与主机名的对应.

  6. Linux遗忘命令

    1.查找文件的安装目录,拿nginx来说 find /|grep nginx.conf 2.   a.查询某个端口是否被占用,如8080端口 netstat –apn | grep 8080 b.查看 ...

  7. Tomcat+Jenkins+SonarQube+SVN+Maven 集成自动化环境搭建(Windows10环境下)

    说在前面的话: 从接到任务到完成共用了7天的时间.正常人用不到这个时间. 此时的功能表现是: 登录本地JenKins对项目进行构建,能够自动从SVN读取最新代码并按照Maven项目构建,构建完成能够自 ...

  8. EF为什么向我的数据库再次插入已有对象?(ZT)

    最近做了个多对多对实体对象,结果发现每次只要增加一个子实体,就会自动添加一个父实体进去,而不管该父实体是否已经存在. 找了好久,终于找到这篇文章,照文章内容来看,应该是断开连接导致的. 原文地址:ht ...

  9. 基于SAE的Python+Django部署

    本文主要参考:http://www.cnblogs.com/qtsharp/archive/2012/01/12/2320774.html,另外包括自己的实际操作. 一.申请SAE帐号以及创建应用ya ...

  10. 推荐一个高大上的网易云音乐命令行播放工具:musicbox

    网易云音乐上有很多适合程序猿的歌单,但是今天文章介绍的不是这些适合程序员工作时听的歌,而是一个用Python开发的开源播放器,专门适用于网易云音乐的播放.这个播放器的名称为MusicBox, 特色是用 ...