题目

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. ufunc函数

    无灯可看.雨水从教正月半.探茧推盘.探得千秋字字看. 铜驼故老.说著宣和似天宝.五百年前.曾向杭州看上元. ufunc是universal function的缩写,他是一种对数组的每个元素进行运算的函 ...

  2. IDEA Maven Hadoop调试hdfs程序

    IDEA 远程调试 Hadoop 两大特色:一是采用maven的pom配置:二是直接连接hdfs:9000端口,无须另外在服务端配置参数. 其实内容包含了两种方式:本地与远程调试.这里仅仅只是使用远程 ...

  3. 使用Ctex中遇到的一些问题

    一般下载好Ctex,我是使用Latex+dvi2pdf完成编译的,但是发现推荐的使用为:1)运行CCT & Latex命令生成两次dvi和ps文件 2)使用dvi2pdf编译dvi文件生成pd ...

  4. 洛谷 P4135 作诗

    分块大暴力,跟区间众数基本一样 #pragma GCC optimize(3) #include<cstdio> #include<algorithm> #include< ...

  5. sql 语句操作,修改字段中字符串的一部分

    update 表名 set 字段=replace(字段,‘替换的部分’,‘替换后的字符串’): update 表名 set A=replace( A, '海淀', '朝阳') where A like ...

  6. 1-18String类简介

    字符串(String)的不可变性 String类在java.lang包下面,是Object类的直接子类,通过API或者源码可以看到,String类是final修饰的,这说明String类不能被继承. ...

  7. pkill 和 pgrep总结

    查看进程ID和方便kill进程 pgrep -d 指定分隔符 pgrep -d ' ' -u root 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 -u p ...

  8. 《Redis开发与运维》快速笔记(一)

    1.前言&基本介绍 在原始的系统架构中,我们都由程序直接连接DB,随着业务的进一步开展,DB的压力越来越大,为了缓解DB的这一压力,我们引入了缓存,在程序连接DB中加入缓存层, 从而减轻数据库 ...

  9. AJPFX关于面向对象之封装,继承,多态 (下)

    (3)private: 对于对于成员来说:只能在该成员隶属于的类中访问. 对于类来说:类不可以声明为private. 4)protected: 对于对于成员来说:相同包中的类可以访问(包访问权限):基 ...

  10. CF779B(round 402 div.2 B) Weird Rounding

    题意: Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the ...