题目

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. 关于使用IQKeyBoardManager键盘还是被遮挡的问题解决方案

    今天在做一个登录界面的时候发现使用了IQKeyBoardManager键盘还是被遮挡,解决方案如下 解决方案一:在所有视图的最外层添加一个UIView作为容器即可,但在有导航栏的情况下导航栏会跟着向上 ...

  2. 跟我一起玩Win32开发(9):绘图(B)

    我们今天继续涂鸦,实践证明,涂鸦是人生一大乐趣. 首先,我们写一个程序骨架子,以便做实验. #include <Windows.h> LRESULT CALLBACK MainWinPro ...

  3. bzoj 5017 [Snoi2017]炸弹

    题面 https://www.lydsy.com/JudgeOnline/problem.php?id=5017 题解 如果数据范围小一点那么就缩点 然后跑一个基础的DAG上的dp就好了 但是边数是$ ...

  4. C/C++程序计时函数gettimeofday的使用

    linux 环境下 用 clock_t发现不准. 换用 //头文件 #include <sys/time.h> //使用timeval start, end;   gettimeofday ...

  5. 机器学习概念之特征选择(Feature selection)之VectorSlicer算法介绍

    不多说,直接上干货! VectorSlicer 算法介绍: VectorSlicer是一个转换器,输入特征向量,输出原始特征向量子集.VectorSlicer接收带有特定索引的向量列,通过对这些索引的 ...

  6. PHP生成和获取XML格式数据

    在做数据接口时,我们通常要获取第三方数据接口或者给第三方提供数据接口,而这些数据格式通常是以XML或者JSON格式传输,本文将介绍如何使用PHP生成XML格式数据供第三方调用以及如何获取第三方提供的X ...

  7. 动手实现 Redux(二):抽离 store 和监控数据变化

    上一节 的我们有了 appState 和 dispatch: let appState = { title: { text: 'React.js 小书', color: 'red', }, conte ...

  8. 通用maper无法获取实体类com.qmtt.model.PhWxUser对应的表名问题

    spring boot在采用了热加载后,可能会出现“无法获取实体类com.qmtt.model.PhWxUser对应的表名!”的异常, 解决办法 在resources新建一个文件夹META-INF,新 ...

  9. 使用原生javascript实现jquery的$(function(){ })

    在使用jquery的时候,经常用到$(function(){})方法或者是$(document).read(function(){})来作为页面dom节点加载完成之后javascript的执行入口,现 ...

  10. 【转】彻底解析Android缓存机制——LruCache

    彻底解析Android缓存机制——LruCache 关于Android的三级缓存,其中主要的就是内存缓存和硬盘缓存.这两种缓存机制的实现都应用到了LruCache算法,今天我们就从使用到源码解析,来彻 ...