Count Positive Bits

11 Dec 2020 - Syed Muhammad Shahrukh Hussain

Write a function to count number of positive bits or ‘1’ for an integer input.

Brief

This program will create a function int count_1_bits(int num) and return total count of positive bits.

C

#include <stdio.h>

int count_1_bits(int num)
{
    int count = 0;
    while( num != 0 ) {        
        if (num & 1) count++; /// check left most bit is on/off
        num = num >> 1; // shift number by 1 bit left.
    }
    return count;
}

int main () {

    printf ("Number of bits: %d", count_1_bits(10));
    return 0;
}

Python

def count_1_bits(num):
    count = 0;
    while ( num != 0 ):
        if (num & 1):
            count =  count + 1; # check left most bit is on/off
        num = num >> 1; # shift number by 1 bit left.
    return count;

print (count_1_bits(10));