Skip to content

Commit

Permalink
Merge pull request neetcode-gh#3114 from Wirgiliusz/main
Browse files Browse the repository at this point in the history
Update 0007-reverse-integer.c with proper solution
  • Loading branch information
a93a authored Nov 7, 2023
2 parents 28c9b4d + 778460c commit 6ab6549
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions c/0007-reverse-integer.c
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
int reverse(int x) {
long reversed_num = 0;
while (x != 0) {
reversed_num = reversed_num * 10 + x % 10;
x /= 10;
int reverse(int x){
int res = 0;

while (x) {
int digit = x % 10;
if ((res > INT_MAX / 10) ||
(res < INT_MIN / 10) ||
(res == INT_MAX / 10 && digit > INT_MAX % 10) ||
(res == INT_MIN && digit > INT_MIN % 10)) {
return 0;
} else {
res *= 10;
}
res += digit;

x = x / 10;
}

if (reversed_num < INT_MIN || reversed_num > INT_MAX)
return 0;

return reversed_num;

return res;
}

0 comments on commit 6ab6549

Please sign in to comment.