Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:
突然发现,二分真TM的是万能的。还有牛顿迭代法,数学的东西,头疼不想看了。还有传说中的“魔数”法,比math库效率都高,试了下RE - -。
C++:
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 5 if(x < 0) 6 return 0; 7 if(x == 0 || x == 1) 8 return x; 9 10 unsigned long long beg = 0; 11 unsigned long long end = (x + 1) / 2; 12 unsigned long long mid = 0; 13 unsigned long long mids = 0; 14 15 while(beg < end) 16 { 17 mid = beg + (end - beg)/2; 18 mids = mid * mid; 19 20 if(mids == x) 21 { 22 return mid; 23 } 24 else if(mids > x) 25 { 26 end = mid - 1; 27 } 28 else 29 { 30 beg = mid + 1; 31 } 32 } 33 34 mids = end * end; 35 if(mids > x) 36 return end - 1; 37 else 38 return end; 39 } 40 };
时间: 2024-10-09 11:34:23