⨊,HowGan

Mi problem is the following: "Write a program that reads from the input a positive integer, and outputs the number that is obtained from the input number by crossing out all even digits. For example, given the input 123456 the output must be 135. In case all digits of the input are even, the output must be...

sponsored
3 months ago 2

Answers

sponsored
  1. Gene

    If you modulo, it's tricky to ensure that you emit the digits in the correct order. To me, it's easier to convert the number to a string, then emit digits in order when they are odd. Remember whether you emit anything because, if you emit nothing, you want to print "0" at the end.

    int
    main (void) {
    int n;
    char str[50];
    int did_print = 0; /* treat as a boolean */ /* Get our positive integer */
    scanf ("%d", &n);
    if (n <= 0) {
    printf ("Integer must be positive.");
    exit (1);
    }
    /* Turn it into characters */
    sprintf (str, "%d", n);
    /* Loop over the string, emitting characters when
    * they are for odd digits. Since there aren't
    * many odd digits, we'll inline them in a SWITCH
    * here. In a fancier program, or if you for some
    * reason have more cases, you'd probably put the
    * decision in a predicate (a function of one
    * argument that returns true or false).
    * Note that we are re-using N here to iterate over
    * the characters in the string. We've already
    * converted the integer to a string; it's in str[].
    * So we don't need N any more, so we'll use it as
    * an index into str[]. */
    n = 0;
    while (str[n] != '') {
    switch (str[n]) {
    case '1':
    case '3':
    case '5':
    case '7':
    case '9':
    printf ("%c", str[n]);
    did_print = 1;
    }
    ++n;
    }
    if (!did_print) { printf ("0"); }
    printf ("n");
    exit (0);
    }

  2. EddieJ

    Use the modulo (%) operator.

    123456 % 10 --> 6 (the rightmost digit)
    123456 / 10 --> 12345
    12345 % 10 --> 5 (the next digit)

    6 % 2 --> 0, because 6 is even
    5 % 2 --> 1, because 5 is odd

Leave A Reply

 Prev Questions

Next Questions