reversing a long sequence in c

Asked

Viewed 57 times

0

I need to invert a sequence of numbers, for example, if 1234 is inserted, I print 4321. The code is working, but for Type 0123 or Type 1230 entries the zero is simply "deleted", but I needed the zero also to be displayed on the screen. I couldn’t think or find a solution to this, someone can help me?

int main()
{
    long n;
    long inverso;

    scanf("%ld",&n);

    do
    {
        inverso=n%10;
        printf("%ld",inverso);
        n/=10;

    }while(n>0);
    printf("\n");
    return 0;
}
  • n need to be long? 0 the left will always be ignored for long, this is normal. 0123 is the same thing as 123. The same happens with 1230, initially 0 is there, because it is 1.230, after reversing the same happens and it happens to be 321.

  • For me, with the ticket 1230 worked perfectly. To 0123, in fact, 0 is ignored for the reason explained above.

  • yes it needs to be long, this is a lot of URI, number 1984, for those who know the URI...

  • Statement: https://www.urionlinejudge.com.br/judge/en/problems/view/1984

  • If you ask as input a number can not have a 0 at the beginning.

1 answer

1

Use the 0* specifier to specify the size of the field to be printed with zeros on the left. For example for a 5-position field:

printf("%0*lld\n", 5, 123);

In your case you need to determine the size of the field that can be done, for example by printing the original number into a string (sprintf) and using the strlen function of .

  • I don’t quite understand how I’m going to apply this in my program, but from what I understand this printf will put a 0 on the exits of any and every input,.

  • Only if the number to be printed does not reach the number of digits defined in the first parameter (in the case of 5).

  • 1

    See test at: http://ideone.com/cZG26Q

Browser other questions tagged

You are not signed in. Login or sign up in order to post.