Exercise: transform decimal to binary and find 1's

-1

#include<stdio.h>intmain(){intk,repeticao;intvalor,numero;intparidade=0;scanf("%d", &repeticao);

for( k = 0; k < repeticao; k++ ){
    int numero,sequencia;
    scanf("%lld", &numero);
    valor = numero/2;
    while( valor != 0 ){
        sequencia = numero%2;
        if( sequencia == 1)
        {
            paridade++;
        }
        numero = valor;
        valor = numero/2;
        if (valor == 0)
    {
        paridade++;
    } 

    }

    printf("%d\n", paridade);
    paridade = 0;
}
return 0;

}

My code is working for the two inputs given in the example: 3 and 21, but in the third entry it returns 15, instead of 50. (123456789123456789) my output is 1 (wrong too) when I put only one repetition (123456789), my output is correct (16), the third input is the repetition of 1 to 9 (3 times), and when I repeat it twice (123456789123456789) . Can you help me please?

    
asked by anonymous 31.01.2017 / 03:21

1 answer

2

Here is a simplified and properly commented solution to determine the number of bits of an integer. As it is an exercise and not a practical problem. I recommend you study the code and understand how it works.

#include<stdio.h>

int main()
{
//variavel que recebera o inteiro
int a;
scanf("%d", &a);
//contador de bits setados como 1
int p = 0;

//enquanto a for maior que zero...
while (a > 0) {
    //verifica se a é impar
    if (a%2!=0) {
        p++;
    }
    //realiza divisões sucessivas 
    a = a/2;

}    

printf("Saída:%d",p);

}

Update:

The calculation does not work for the third case, as the value extrapolates the storage capacity of int, long, long long int ....

  

prog.cpp: 7: 32: warning: integer constant is too large for its type        unsigned long long int a = 123456789123456789123456789;

    
31.01.2017 / 04:07