Enter a Number (in decimal) and Find Number of 1's in its Binary Pattern (Commented)

22:38 0 Comments A+ a-

Problem:
Write a function named ‘countOnes’, which receives an integral value (base 10) and returns the

number of ones in its binary patterns.
Solution:
# include <iostream>
# include <cmath>
using namespace std;
int countOnes(int dec); //countOnes function prototype written with int dec as a parameter and count number of ones in the binary of the digit entered in decimal
int main()
{
int decimal; //decimal variable taken to store a base 10 number in it
cout << "Please enter an Integer (Base 10) : ";
cin >> decimal; //input stored in decimal variable
cout << "The Number of Ones in the Binary Pattern Of " << decimal << " is : " << countOnes(decimal) << endl; //number of 1's in the binary pattern of digit entered displayed by calling the function countOnes with argument decimal

system("pause");
return 0;

}
int countOnes(int dec) //defining of function countOnes
{
int revBin = 0,count=0,r=0; //revBin stores the inverted binary pattern of the dec(digit), count variable counts the number of 1's in binary pattern of digit, and r just stores the result of revBin%10 means last digit of revBin

while (dec != 0) //runs until dec doesn't become 0
{
revBin = revBin * 10 + dec % 2; //Reverse binary of dec(digit) stored in it
dec = dec/ 2; //dec(digit) is divided by 2 to calculate next digit of binary
}
while (revBin != 0) //runs until revBin doesn't become 0
{
r = revBin % 10; //last digit of revBin separated and stored in r
revBin = revBin / 10; //revBin is divided by 10 to remove last digit
if (r == 1) // check if r is equal to 1
{
count++; //if r=1 then count is increased by 1
}
}
return count; //count returned to statement which called it

}