How to check if a number overflows an 'int'

c, integer-overflow

Solution

(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:

- Are you allowed to use `unsigned long long` / `uint64_t` (64 bit int)?

- Where is the string coming from? `stdin` / read from file / hard-coded as a string literal?

- Is it given to you as a Decimal representation? Binary / Octal / Hex?

- What kind of error should be thrown? Do we try to recover and continue execution? What's the fail-safe default value?

Assuming that your interviewer tells you that it's in Decimal representation + you can use `unsigned long long`:

- First check the number of digits: 32-bit `unsigned int` ranges between `0 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.

- Next, save the number into an `unsigned long long` and divide by `UINT32_MAX+1=4294967296`. If the result is greater than `0`, it overflows; raise error.

Problem

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 ?

Original source

Related problems