-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
7.c :reverse of a number with overflow check added #310
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
| @@ -0,0 +1,35 @@ | |||
| int reverse(int x){ | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So many checking here. I have a good solution for it:
int reverse(int x){
long res = 0;
while (x != 0)
{
int tail = x % 10;
res = res * 10 + tail;
/* Check overflow */
if (res > INT_MAX || res < INT_MIN)
return 0;
x = x / 10;
}
return (int)res;
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here you are using long int. What if the system we are using, supports up to 32-bit? What if the OS does not support long int?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The question is not limit only for 32-bit.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah if we don't put that restriction then it will work. So do you want me to change and re-push?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You can put the comment on your way, it works only for 32-bit system. And then adding my solution below. Thank you
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Committed the changes. Thanks
leetcode/src/9.c
Outdated
| @@ -0,0 +1,50 @@ | |||
|
|
|||
|
|
|||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
a better solution:
int reverse(int x){
long res = 0;
while (x != 0)
{
int tail = x % 10;
res = res * 10 + tail;
/* Check overflow */
if (res > INT_MAX || res < INT_MIN)
return 0;
x = x / 10;
}
return (int)res;
}
bool isPalindrome(int x) {
if (x < 0)
return 0;
else
return x == reverse(x);
}
Merge pull request TheAlgorithms#310 from SuranjanDaw/master
No description provided.