Multiply even index values of a string in C

Asked

Viewed 388 times

0

The question I need to solve is the following: The person gives a number, I need to multiply by 2 all the numbers that are in the "index" even, the problem is that the index starts at 1 on the right. For example, the number 49927398716 would be rewritten as 4(18)9(4)7(6)9(16)7(2)6.

My reasoning was: invert the number so that I can multiply the indices [i] + 1 * 2. I was able to invert, however, when I multiply the numbers, the program returns letters instead of numbers.

Code:

void checkfinal(char num[]){    
    int tamanho = strlen(num);
    char aux[50];   
    int i, j=0;

    for(i= tamanho-1;i>=0;i--){
        aux[j]=num[i];
        j++;
    }

    aux[j]=0;

    for( j = 1; j <= tamanho; j++)
    {

       if(j%2==0){
           aux[j-1] = aux[j-1] * 2;
       }
    }

    printf("%s", aux);
}
  • The problem is very ill-defined so you can interpret it in several ways and the question does not have a specific question. So I think there are several errors in the algorithm. and probably the solution shouldn’t even be this.

1 answer

1

No reversal is required, it is sufficient to determine whether the total digits are even or odd.

#include <stdio.h>
#include <string.h>
int main() {
    char num[1024], result[2048]="", aux[3];
    int i, incr;
    printf("Informe o número: ");
    gets(num); /* seria melhor fgets */
    incr = (strlen(num) % 2 == 0) ? 1 : 0;
    for (i=0; i<strlen(num); i++) {
        sprintf(aux, "%d", (i%2 == incr) ? num[i]-'0': (num[i]-'0') * 2);
        strcat(result, aux);
    }
    printf("Original: %s\nModificado: %s", num, result);
    return 0;
}

Browser other questions tagged

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