I try to write a program for reverse the user input number.
The user input range is from 0 < a < 4294967295, here is EDITED code.
unsigned long int reverseNumber(unsigned long int num)
{
unsigned long int rev = 0;
while (num > 0)
{
rev = rev *10 + (num%10);
num = num/10;
}
return rev;
}
The problem is when I input 4294967295, it will output 1632727628. Why? I have no idea why it happened. How can I reverse the 4294967295.
I had changed it to unsigned long int, printf by using %lu, but still output 1632727628. Why?
The reverse of 4294967295 is 5927694924 which is greater than the range of unsigned int
In your system, unsigned int is 32-bit wide, hence the max value that an unsigned int can represent is 4294967295 i.e. 0xFFFFFFFF. That is why your result is overflowing and whatever remains in 32 bits is shown as output.
If you represent 5927694924 in hex, it is 0x16151724C which has extra 33rd bit 1, which is discarded and hence output is 0x6151724C which is 1632727628 in decimal.
To print it on screen you need a greater data type like unsigned long long or uint64_t or unsigned long (on 64-bit systems only), whatever your compiler supports for 64 bit integers.
The reverse of 4294967295 is 5927694924, which is greater than 4294967295, which is the greatest integer which can be stored on 32 bit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With