Lanqiao Cup-Algorithm Training-6-2 Recursively Find Binary Representation Bits

topic


Problem description
  Given a decimal integer, return the number of bits in the corresponding binary number. For example, if you enter the decimal number 9, the corresponding binary number is 1001, so the number of digits is 4.
Sample input
An input sample that meets the requirements of the question.
9
sample output
corresponding to the output of the input sample above.
Insert picture description here


Ideas

To solve this problem, we can always use an infinite loop to judge whether the i-th power of 2 is greater than n. If it is greater than n, the number of binary digits must be i at this time, because we start from the 0th time of 2, and all actual The number of digits displayed during operation is i-1. Personally, I think it should be a better solution.


Code

#include <stdio.h>
#include<math.h>
int main()
{
    
        
	int n,i;
	scanf("%d",&n);
	for(i=0;;i++){
    
    
		if(pow(2,i)>n){
    
    
			printf("%d\n",i);
			break;
		}
	}
	return 0;
}
结果:
9
4

--------------------------------
Process exited after 1.452 seconds with return value 0
请按任意键继续. . .

Guess you like

Origin blog.csdn.net/mjh1667002013/article/details/114457310