Problem Description:
Suppose you have an integer number ‘N’ full of only one and zero. Your task is to find out total number of one and total number of zero separately.
Note: N is at most 30000.
Discussion:
declare three variable n, c0, c1.
n=given integer number
c0=number of zeroes
c1=number of ones
Now take an integer input n less than 30001.
Now scan number n digit by digit until it is converted into a single digit. Divide number n by 10 and take the remainder r. if r is equal to 0 then increase the counter of c0 by 1 and when the value of r is equal to 1, increase the counter of c1 by 1 at each iteration. Then update the value of n by dividing it by 10 and save it to the variable n.
When the value of n is converted into single digit just print the value of c0 and c1 representing number of zeroes and number ones respectively.
Source Code:
#include <stdio.h>
int main() {
int n, c0 = 0, c1 = 0;
printf(“Enter an integer: “);
scanf(“%d”, &n);
while (n > 0) {
int r = n % 10;
if (r == 0) {
c0++;
} else if (r == 1) {
c1++;
}
n /= 10;
}
printf(“Number of 0’s: %d\n”, c0);
printf(“Number of 1’s: %d\n”, c1);
return 0;
}