Skip to content

Commit

Permalink
Merge pull request #39 from NabhiA/main
Browse files Browse the repository at this point in the history
Added solution for sqrt(x) problem of LeetCode. Problem #69
  • Loading branch information
iamdestinychild authored Oct 3, 2023
2 parents 3960a1d + 517d112 commit c2b6b79
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
Binary file added LeetCode/Sqrt(x)/C++/Screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
52 changes: 52 additions & 0 deletions LeetCode/Sqrt(x)/C++/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include <iostream>
using namespace std;

class Solution {
public:

long long int binarySearch(int n){
int s=0;
int e=n;
long long int mid = s+(e-s)/2;
long long int ans = -1;

while(s<=e){
long long int square = mid*mid;
if(square == n){
return mid;
}
if(square < n){
ans = mid;
s=mid+1;
}
else{
e=mid-1;
}
mid = s+(e-s)/2;
}
return ans;
}
int mySqrt(int x) {
return(binarySearch(x));
}
};

int main(){

Solution solution;

int num = 8;

long long result = solution.mySqrt(num);

if (result)
{
cout<<result;
}
else
{
cout << "No solution found." << endl;
}

return 0;
}
29 changes: 29 additions & 0 deletions LeetCode/Sqrt(x)/PROBLEM.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/description/)

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.



```example 1
Example 1:
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.
```

```example 2
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
```

```constrants
Constraints:
0 <= x <= 231 - 1
```

0 comments on commit c2b6b79

Please sign in to comment.