How to handle the test case if I enter the number 10000 and I get 1 as a result instead of getting 00001. How to handle this case?
#include <stdio.h>
int main() {
int n, rev = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0) {
remainder = n % 10;
rev = rev * 10 remainder;
n /= 10;
}
printf("Reversed number = %d", rev);
return 0;
}
CodePudding user response:
Keep track of the number of digits in your number, and then print the number with a formatted length:
int numDigits = 0;
while (n != 0) {
...
numDigits ;
}
and then:
printf("Reversed number = %.*d", numDigits, rev);
CodePudding user response:
Use %n
specifier to count the number of digits entered. Note the space before the first %n
to skip any whitespace. Also this will fail if the input is not an integer in range.
Then use the number of digits to pad the output %0*d
with leading zeros.
Try with input of 10000
and 00001
.
#include <stdio.h>
int main ( void) {
int n, rev = 0, remainder;
int start = 0;
int stop = 0;
printf ( "Enter an integer: ");
scanf ( " %n%d%n", &start, &n, &stop);
int digits = stop - start;
while ( n != 0 || digits) {
--digits;
remainder = n % 10;
rev = rev * 10 remainder;
n /= 10;
}
printf ( "Reversed number = %0*d", stop - start, rev);
return 0;
}
outout:
Enter an integer: 00002
Reversed number = 20000
Enter an integer: 3000
Reversed number = 0003
CodePudding user response:
Read the input as a string and reverse it, if you use windows you have the string.h
handy strrev()
:
char n[20];
printf("Enter an integer: ");
scanf("s", n);
printf ("%s", strrev(n));
Otherwise you have to make your own, here's a nice one using biwise XOR:
char *strrev(char *str)
{
char *substr_lh, *substr_rh;
if (! str || ! *str)
return str;
for (substr_lh = str, substr_rh = str strlen(str) - 1;
substr_rh > substr_lh;
substr_lh, --substr_rh)
{
*substr_lh ^= *substr_rh;
*substr_rh ^= *substr_lh;
*substr_lh ^= *substr_rh;
}
return str;
}
You can add validation for non digit characters which, I reckon , is trivial.
CodePudding user response:
In general the reversed number can not fit in an object of its type.
It is better to use the type unsigned int
instead of the type int
. Otherwise you can get an unexpected result.
What you need is just to output the reversed number in a field with the width equal to the number of digits in the entered number prefixed with zeroes if required.
Here is a demonstrative program.
#include <stdio.h>
int main(void)
{
const unsigned int Base = 10;
unsigned int n = 0;
printf( "Enter an integer: " );
scanf( "%u", &n );
unsigned int rev = 0;
int count = 0;
do
{
rev = rev * Base n % Base;
count;
} while ( n /= Base );
printf( "Reversed number = %0*u", count, rev );
return 0;
}
The program output might look like
Enter an integer: 10000
Reversed number = 00001