NC32. 求平方根
描述
示例1
输入:
2
输出:
1
示例2
输入:
2143195649
输出:
46294
C++ 解法, 执行用时: 1ms, 内存消耗: 392KB, 提交时间: 2017-06-10
class Solution { public: int sqrt(int x) { if(x <= 1)return x; int begin = 1; int end = x; int middle = 0; while(begin<=end) { middle = (begin + end)/2; //不要写成middle*middle==x,会溢出 if(middle==x/middle) { return middle; } else { if (middle<x/middle) { begin = middle + 1; } else { end = middle - 1; } } } //结束条件end一定<begin,所以返回end return end; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 320KB, 提交时间: 2021-02-02
class Solution { public: /** * * @param x int整型 * @return int整型 */ int sqrt(int x) { int i = 1; int res = 0; while(x >=0){ x -= i; ++res; i += 2; } return res-1;// write code here } };
C++ 解法, 执行用时: 2ms, 内存消耗: 324KB, 提交时间: 2021-03-21
class Solution { public: /** * * @param x int整型 * @return int整型 */ int sqrt(int x) { // write code here if(x==0||x==1) return x; int l=0,r=x,res=-1; while(l<=r){ int mid=l+(r-l)/2; if((long long)mid*mid<=x){ res=mid; l=mid+1; }else{ r=mid-1; } } return res; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 328KB, 提交时间: 2021-06-05
class Solution { public: /** * * @param x int整型 * @return int整型 */ int sqrt(int x) { if (x<2) { return x; } int left=1; int right=x/2; int mid=1; while (left<=right) { mid=(left+right)/2; if (x/mid==mid) { return mid; } else if (x/mid<mid) { right=mid-1; } else{ left=mid+1; } } return right; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 328KB, 提交时间: 2021-05-17
class Solution { public: /** * * @param x int整型 * @return int整型 */ int sqrt(int x) { // write code here if(x<0) return -1; int i = 1; int j = x; int mid; while(i<=j){ mid = (i+j)>>1; if(mid*mid==x) return mid; if(mid>x/mid) j = mid-1; else i = mid+1; } return j; } };