Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added solution for sqrt(x) problem of LeetCode. Problem #69 #39

Merged
merged 1 commit into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
```
Loading