Skip to content
Open
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
33 changes: 33 additions & 0 deletions dart/sqrtx.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
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.
*/

class Solution {
int mySqrt(int x) {
if (x < 2) {
return x;
}

int left = 1;
int right = x ~/ 2;
int ans = 1;

while (left <= right) {
final int mid = left + ((right - left) ~/ 2);
final int square = mid * mid;

if (square == x) {
return mid;
} else if (square < x) {
ans = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}

return ans;
}
}