Leetcode notes: Sqrt (x)
I. Description
Implement int sqrt (int x ).
Compute and return the square root of x.
Ii. Question Analysis
This question requires the implementation of the root formula. This question is relatively simple, because you only need to return the nearest integer and directly use the binary method. There are still some details in the implementation process, such as the judgment conditions:x / mid > midBut notx > mid * midBecausemid * midWill cause overflow.
Iii. Sample Code
# Include
Using namespace std; class Solution {public: int sqrt (int x) {if (x = 0 | x = 1) return x; int min = 1, max = x/2; // The root must be in this range // Binary Search int mid, result; while (min <= max) {mid = min + (max-min) /2; if (x/mid> mid) {// the square of the root must be less than or equal to x. Therefore, the root value result = mid must be updated each time; min = mid + 1;} else if (x/mid <mid) max = mid-1; else return mid;} return result ;}};
Some running results:
Iv. Summary
This is one of the classic questions about the idea of Governance Division.