本文共 846 字,大约阅读时间需要 2 分钟。
实现函数 int sqrt(int x).
计算并返回x的平方根(向下取整)
class Solution { public: /** * * @param x int整型 * @return int整型 */ int sqrt(int x) { // write code here if(x < 2){ return x; } int left = 1, right = x / 2; int mid ,approximate_solution; while(left <= right){ mid = (left + right )/ 2; // 避免mid*mid越界 // mid 小了, left移到mid的右边 if(x / mid > mid){ left = mid + 1; approximate_solution = mid; }else if( x / mid < mid){ right = mid - 1; } else{ return mid; } } return approximate_solution; }};
转载地址:http://mydg.baihongyu.com/