Leetcode brush inscription (17) -x square root

Topics requirements:

Achieve int sqrt (int x) function.

Computes and returns the square root of x, where x is a non-negative integer.

Since the return type is an integer, the integer part of the result to retain only the fractional part is rounded down.

answer:

After the first reaction is subject to get: plus one half the square of the digital certainly larger than this number, so the traversal between 0 to add half a: When traversing the square of each of a number smaller than this number, plus a traversal ; otherwise the index by one that is the square root of the whole removed.

But when this last test, when faced with super large numbers to be wrong, but this time to traverse the high degree of complexity.

Improved method is: the dichotomy!

Initialization: left margin is 0, the right border of half plus one digit;

Take the value! Note here that the value declared as long type, otherwise large numbers will overflow, and here's value should take on the whole rather than at the whole, or will enter an infinite loop! ! !

 

 

Guess you like

Origin www.cnblogs.com/wangjm63/p/11520196.html