Lintcode: Sqrt(X)
C++
1 class Solution { 2 public: 3 /** 4 * @param x: An integer 5 * @return: The sqrt of x 6 */ 7 int sqrt(int x) { 8 // write your code here 9 if (x<=1) { 10 return x; 11 } 12 int left = 1; 13 int right = x; 14 while (left <= right) { 15 int mid = left + ((right - left) >> 1); 16 if (mid == x/mid) { 17 return mid; 18 } 19 else if (mid < x/mid) { 20 left = mid + 1; 21 } else { 22 right = mid - 1; 23 } 24 } 25 return right; 26 } 27 };
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。