Sqrt(x) Solutions in C++
Number 69
Difficulty Easy
Acceptance 34.0%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/sqrtx/// Author : Hao Chen// Date : 2014-08-26#include <stdlib.h>#include <iostream>using namespace std;int sqrt(int x) {if (x <=0 ) return 0;//the sqrt is not greater than x/2+1int e = x/2+1;int s = 0;// binary searchwhile ( s <= e ) {int mid = s + (e-s)/2;long long sq = (long long)mid*(long long)mid;if (sq == x ) return mid;if (sq < x) {s = mid + 1;}else {e = mid - 1;}}return e;}// http://en.wikipedia.org/wiki/Newton%27s_methodint sqrt_nt(int x) {if (x == 0) return 0;double last = 0;double res = 1;while (res != last){last = res;res = (res + x / res) / 2;}return int(res);}int main(int argc, char**argv){int n = 2;if( argc > 1 ){n = atoi(argv[1]);}cout << "sqrt(" << n << ") = " << sqrt(n) << endl;return 0;}
C++ solution by pezy/LeetCode
class Solution {public:int sqrt(int x) {int l = 1, r = x, ret = 0;while (l <= r) {int m = (l + r) >> 1;if (m <= x / m) { l = m+1; ret = m; }else r = m-1;}return ret;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/sqrtx/description//// Author : liuyubobobo/// Time : 2018-06-18#include <iostream>using namespace std;/// Binary Search/// Time Complexity: O(log(MAX_INT))/// Space Complexity: O(1)class Solution {public:int mySqrt(int x) {int l = 0, r = x;while(l < r){long long mid = l + ((long long)r - l + 1) / 2;if(mid * mid <= (long long)x)l = mid;elser = mid - 1;}return l;}};int main() {cout << Solution().mySqrt(4) << endl;cout << Solution().mySqrt(8) << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/sqrtx/description//// Author : liuyubobobo/// Time : 2019-04-03#include <iostream>using namespace std;/// Binary Search/// Using double first////// Time Complexity: O(log(MAX_INT) * precision)/// Space Complexity: O(1)class Solution {private:double e = 1e-6;public:int mySqrt(int x) {double l = 0.0, r = INT_MAX;while(r - l >= e){double mid = (l + r) / 2;if(mid * mid <= x)l = mid;elser = mid;}return (int)r;}};int main() {cout << Solution().mySqrt(4) << endl;cout << Solution().mySqrt(8) << endl;return 0;}