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: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
bf6b1a5
commit b2fc80d
Showing
2 changed files
with
46 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 divide.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,44 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
#include <limits.h> | ||
|
||
int divide(int dividend, int divisor) { | ||
int sign = (float)dividend / divisor > 0 ? 1 : -1; | ||
unsigned int dvd = dividend > 0 ? dividend : -dividend; | ||
unsigned int dvs = divisor > 0 ? divisor : -divisor; | ||
|
||
unsigned int bit_num[32]; | ||
unsigned int i = 0; | ||
long long d = dvs; | ||
bit_num[i] = d; | ||
while (d <= dvd) { | ||
bit_num[++i] = d = d << 1; | ||
} | ||
i--; | ||
|
||
unsigned int result = 0; | ||
while (dvd >= dvs) { | ||
if (dvd >= bit_num[i]) { | ||
dvd -= bit_num[i]; | ||
result += (1<<i); | ||
} else { | ||
i--; | ||
} | ||
} | ||
|
||
//becasue need to return `int`, so we need to check it is overflowed or not. | ||
if (result > INT_MAX && sign > 0) { | ||
return INT_MAX; | ||
} | ||
return (int) result * sign; | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
if (argc != 3) { | ||
fprintf(stderr, "Usage: ./test dividend divisor\n"); | ||
exit(-1); | ||
} | ||
printf("%d\n", divide(atoi(argv[1]), atoi(argv[2]))); | ||
return 0; | ||
} |