forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Leo Ma <[email protected]>
- Loading branch information
1 parent
48af54f
commit 46c62dc
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
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,2 @@ | ||
all: | ||
gcc -O2 -o test sqrt.c |
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,35 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
|
||
static int mySqrt(int x) | ||
{ | ||
if (x == 0) { | ||
return 0; | ||
} | ||
|
||
unsigned int left = 1; | ||
unsigned int right = (unsigned int) x; | ||
for (; ;) { | ||
unsigned int mid = left + (right - left) / 2; | ||
if (mid > x/mid) { | ||
right = mid; | ||
} else { | ||
if (mid + 1 > x/(mid + 1)) { | ||
return mid; | ||
} else { | ||
left = mid; | ||
} | ||
} | ||
} | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
if (argc != 2) { | ||
fprintf(stderr, "Usage: ./test n\n"); | ||
exit(-1); | ||
} | ||
|
||
printf("%d\n", mySqrt(atoi(argv[1]))); | ||
return 0; | ||
} |