题目

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. SOA架构设计和相关案例分析

    一.SOA概念 1.定义: SOA,是一个组件模型,面向服务的体系架构,它将应用程序的不同服务通过这些服务之间定义良好的接口和契约联系起来,不涉及底层编程接口和通讯模型.服务层是SOA的基础,可以直接 ...

  2. 跟我一起玩Win32开发(16):ListView的多个视图

    在上一个例子中,我们只用到了ListView的Report视图,也就是详细视图.本文我们再把上一篇文章中所用的例子进行一下扩展,例子源码可以到俺的资源区下载. 我们为ListView中显示的数据加上图 ...

  3. Hdu 5446 Unknown Treasure (2015 ACM/ICPC Asia Regional Changchun Online Lucas定理 + 中国剩余定理)

    题目链接: Hdu 5446 Unknown Treasure 题目描述: 就是有n个苹果,要选出来m个,问有多少种选法?还有k个素数,p1,p2,p3,...pk,结果对lcm(p1,p2,p3.. ...

  4. window上安装MySQL

    一.安装MySQL 1.1 下载解压缩版的安装包,解压,然后配置环境变量 PATH=.......;D:\Program Files (x86)\mysql-5.5.27-win32\bin (注意是 ...

  5. 关于对象.style currentstyle 的区别

    对象.style的方式只能获取行内写法的样式,但是外部引入的或者写在head里面的就无法获取,只能用currentstyle.

  6. android studio 定时器操作 实现定时执行相关任务

    package ipget.wenzheng.studio.ipget; import android.os.Bundle; import android.os.Handler; import and ...

  7. String 截取字符串#中间的文本

    通过正则实现: String regex = "#([^#]+)#"; @Test public void test() { String text = "#中俄建交七十 ...

  8. MY $MYVIMRC

    set nocompatiblesource $VIMRUNTIME/vimrc_example.vim"source $VIMRUNTIME/mswin.vim"behave m ...

  9. MATLAB学习总结(1)

    MATLAB学习总结(1)   path help path cd(current directory) savepath pathtool

  10. (译)IOS block编程指南 1 介绍

    Introduction(介绍) Block objects are a C-level syntactic and runtime feature. They are similar to stan ...