ImplementInt SQRT (int x)
.
Compute and return the square rootX.
Https://oj.leetcode.com/problems/sqrtx/
Idea 1: the square root of a number must be 0 ~ X/2 + 1, so binary search in this range.
Note:
- Long is used in the intermediate result; otherwise, mid * mid overflows.
- Returns the floor value of the square root if no result is found.
Idea 2: Newton Iteration Method.
Public Class Solution { Public Int SQRT ( Int X ){ If (X <0 ) Return -1 ; Long Right = X/2 + 1 ; Long Left = 0 ; Long Mid; While (Left <= Right) {mid = (Left + right)/2; If (X <mid * Mid) Right = Mid-1 ; Else If (X> mid * Mid) left = Mid + 1 ; Else Return ( Int ) Mid ;} Return ( Int ) Right ;} Public Static Void Main (string [] ARGs) {system. Out. println ( New Solution (). SQRT (0 ); System. Out. println ( New Solution (). SQRT (1 ); System. Out. println ( New Solution (). SQRT (2 ); System. Out. println ( New Solution (). SQRT (3); System. Out. println ( New Solution (). SQRT (4 ); System. Out. println ( New Solution (). SQRT (2147483647 ));}}
View code
Refer:
Http://blog.csdn.net/linhuanmars/article/details/20089131
Http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html