Leetcode 挑战 Day 17 [ 69. Sqrt(x) ]

69. Sqrt(x)


今天我们一起挑战leetcode第69题Sqrt(x)!

题目


Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

Example 1:
Input: x = 4
Output: 2

Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

今天这题要求我们实作一个根号功能,并且不能使用程序语言内建的函式,题目会给我们一个整数,我们要回传此整数开平方根後的结果,并且只需要回传到整数位。

牛顿迭代法


这题我们当然可以用最暴力的解法,用回圈一个个去试有可能的整数,我们知道这样的速度会非常慢。而我们可以透过二分搜寻法,来降低搜寻目标数字的速度。
然而,这题与数学中的牛顿迭代法是有相关的,其中的原理和概念比较偏向数学原理,如果有兴趣可以阅读下列这篇文章。简单来说,牛顿迭代法是在一开始给出一个猜测值,接着不断对这个值进行一些操作(用猜测值与原本题目给的整数做运算),直到求出解答。
https://www.itread01.com/content/1546915711.html

以下是python的程序码

class Solution:
    def mySqrt(self, x: int) -> int:
        guess = 1000  # 猜测值
        while True:
            p = int(guess)
            q = p + 1
            guess = (guess + x / guess) / 2  # 根据牛顿迭代法做出的运算,可以快速接近欲求的数值
            if p**2 <= x and q**2 > x:  # 找到我们要的了!
                break 
        return int(guess)  # 回传整数就好

<<:  【从零开始的Swift开发心路历程-Day8】打造美观的App版面!Constraints约束篇

>>:  this指向who(下)

DAY 5 Big Data 5Vs – Volume(容量) - RedShift

相较於资料湖,另一个更常见的大数据储存系统是 — 资料仓储。和资料湖一样,资料仓储也用来储存巨量资料...

#7 Web Layout: CSS Fundamentals

Final Design CSS Web Layout Tips 1. Horizontally c...

.Net Core Web Api_笔记24_api结合EFCore资料库操作part2_产品分类资料新增_资料查询呈现(带入非同步API修饰)

接续上一篇 在Startup.cs中启用静态资源 於专案新增目录命名为wwwroot(会自动变成地球...

android studio 30天学习笔记-day 7-介绍okhttp

okhttp是常用的第三方库,跟retrofit、Volley一样都能做网络连线的请求。 今天就做个...

Dependency injection

谈到 Android 的 dependency injection (DI),大家一定会想到 Dag...