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

Showing posts with label Binary. Show all posts
Showing posts with label Binary. Show all posts

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 > 1 do

count ← count + 1

n ← 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 n = 1 return 1

else return BinRec(n/2) + 1

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