Possible Duplicate:
Best way to detect integer overflow in C/C++
I was asked this question in an interview : “Convert a string representation of a number into an integer”. But if the number exceeds the max value that can be stored in a 32 bit integer, it must throw an error.
My question is how can we check if a number overflows a 32-bit unsigned int ?
(I looked at the possible duplicate to this question and I’m uncertain how useful that reading will be, since in an interview context, you’d be expected describe the general ideas / approach)
Part of answering interview questions is to ask clarifying questions (one of the important checklist items that interviewers expects from you).
So your line of inquiry should at least include things like:
unsigned long long/uint64_t(64 bit int)?stdin/ read from file / hard-coded as a string literal?Assuming that your interviewer tells you that it’s in Decimal representation + you can use
unsigned long long:unsigned intranges between0 to 4,294,967,295. If the number’s string representation in decimal has more than 10 characters (has more than 10 digits), it already overflows; raise error.unsigned long longand divide byUINT32_MAX+1=4294967296. If the result is greater than0, it overflows; raise error.