Advertisement
rdsedmundo

Paridade.c

Jul 4th, 2013
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.06 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. #define MAX 1024
  5.  
  6. int numOcc(char * str, char srch) {
  7.     int i, Count = 0;
  8.     for(i = 0; i < strlen(str); i++) {
  9.         if(str[i] == srch)
  10.             Count++;
  11.     }
  12.  
  13.     return Count;
  14. }
  15.  
  16. void toBin(char * num, char * dest) {
  17.     unsigned int pNum = atoi(num);
  18.     int i, bin[MAX];
  19.     for(i = 0; i < MAX; i++)
  20.         bin[i] = -1;
  21.  
  22.     i = MAX - 1;
  23.  
  24.     strcpy(dest, "");
  25.  
  26.     while(pNum > 0) {
  27.         bin[i] = pNum%2;
  28.         pNum /= 2;
  29.         i--;
  30.     }
  31.  
  32.     for(i = 0; i < MAX; i++) {
  33.         if(bin[i] == -1)
  34.             continue;
  35.  
  36.         char buffer[2];
  37.         sprintf(buffer, "%d", bin[i]);
  38.  
  39.         strcat(dest, buffer);
  40.     }
  41. }
  42.  
  43. int main(void) {   
  44.     int i;
  45.     char nums[MAX][11];
  46.  
  47.     for(i = 0; i < MAX; i++)
  48.         strcpy(nums[i], "");
  49.    
  50.     i = 0;
  51.     while(1) {
  52.         char aux[10 + 1];
  53.         scanf("%s", aux);
  54.  
  55.         if(strcmp(aux, "0") == 0)
  56.             break;
  57.  
  58.         strcpy(nums[i], aux);
  59.         i++;
  60.     }
  61.  
  62.     i = 0;
  63.     while(1) {
  64.         if(strcmp(nums[i], "") == 0)
  65.             break;
  66.        
  67.         char Bin[MAX];
  68.         toBin(nums[i], Bin);
  69.  
  70.         printf("The parity of %s is %d (mod 2).\n", Bin, numOcc(Bin, '1'));
  71.         i++;
  72.     }
  73.  
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement