Implement int sqrt(int x).

Compute and return the square root of x.

 1 class Solution {
 2 public:
 3     int sqrt(int x) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if(x<=0) return 0;
 7         if(x==1) return 1;
 8         int small=0;
 9         int large=x;
10         int temp=x/2;
11         while(small<large){
12             int a = x/temp;
13             int b = x/(temp+1);
14             if (a==temp) return a;
15             if (b==temp+1) return b;
16             if(temp<a && temp+1>b)
17                 return temp;
18             else if(temp<a && temp+1<b){
19                 small=temp+1;
20                 temp = (small+large)/2;
21             }else {
22                 large = temp;
23                 temp = (small+large)/2;
24             }
25         }
26         return -1;
27     }
28 };
我的答案

相关文章:

  • 2021-10-31
  • 2022-02-19
  • 2021-12-15
  • 2022-12-23
  • 2021-07-18
  • 2021-05-29
  • 2021-10-20
  • 2021-10-26
猜你喜欢
  • 2021-11-21
  • 2021-09-24
  • 2021-08-18
  • 2021-05-31
  • 2021-07-22
  • 2021-07-06
  • 2022-01-01
相关资源
相似解决方案