Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Wednesday, 27 March 2019

Binary Algorithm

ALGORITHM Binary(n)


//Input: A positive decimal integer n

//Output: The number of binary digits in n’s binary representation

count ← 1
while 
n > do

count ← count 1

← n/2

return count

Another Way

ALGORITHM BinRec(n)


//Input: A positive decimal integer n

//Output: The number of binary digits in n’s binary representation

if return 1

else return BinRec(n/21

C program:


// Iterative C program to count the number of


// digits in a number in binary form

#include <stdio.h>

int countDigit(long long n)

{

    int count = 0;

    while (n != 0) {

        n = n /2;

        ++count;

    }

    return count;

}

int main(void)

{

    long long n =1024;

    printf("Number of digits : %d",countDigit(n));
   
     return 0;
}

Output:

Number of digits : 11

0 comments:

Post a Comment