BillHung.Net


powered by FreeFind     sms

HW01

/*
Name: Hung, Bill Chun Wai
Lab section time: Th 5-7
*/

#include <stdio.h>

int bitCount (unsigned int n);

int main ( ) {
printf ("# 1-bits in base 2 representation of %u = %d, should be 0\n",
0, bitCount (0));
printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
1, bitCount (1));
printf ("# 1-bits in base 2 representation of %u = %d, should be 16\n",
1431655765, bitCount (1431655765));
printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
1073741824, bitCount (1073741824));
printf ("# 1-bits in base 2 representation of %u = %d, should be 32\n",
4294967295, bitCount (4294967295));
return 0;
}

int bitCount (unsigned int numToPrintInBase2){
int num=0;
/*if the reminder of the number is 1, add 1 to the count (num)*/
while ( numToPrintInBase2 > 1 ){
if (numToPrintInBase2 % 2 == 1)
num = num + 1;
numToPrintInBase2 = numToPrintInBase2 /2;
}

/*to see the reminder (1 or 0) is 1, then add one to the count(num)*/
if (numToPrintInBase2)
num = num + 1;

return num;
}

/*
Name: Hung, Bill Chun Wai
Lab section time: Th 5-7
*/

#include <stdio.h>

int main ( ) {
unsigned int numToPrintInBase2 = 1431655765; /* alternating 1's and 0' */
unsigned int exp = 1;
int k; /* can't declare variable in a loop header */

/* Compute the highest storable power of 2 (2 to the 31th). */
for (k=0; k<31; k++) {
exp = exp * 2;
}

/* For each power of 2 from the highest to the lowest,
print 1 if it occurs in the number, 0 otherwise. */
for (k=31; k>=0 ; k--) {
if (numToPrintInBase2 >= exp) {
printf ("%d", 1);
numToPrintInBase2 = numToPrintInBase2 - exp;
} else {
printf ("%d", 0);
}
exp = exp / 2;
}
printf ("\n");
return 0;
}