-
Notifications
You must be signed in to change notification settings - Fork 65
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #39 from NabhiA/main
Added solution for sqrt(x) problem of LeetCode. Problem #69
- Loading branch information
Showing
3 changed files
with
81 additions
and
0 deletions.
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
``` |