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 countAnother 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
0 comments:
Post a Comment