C/C++ Programming Learning-Week 21 ⑩ Dividing Power of 2

Topic link

Title description

Given a positive integer n, calculate how many powers of 2 it can divide at most

Input
input a number n

Output
a number

Sample Input

896

Sample Output

7

Ideas

Always divide n by 2. If n%2==0, continue to divide and see how many times it has been removed.

C++ code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	int n;
	while(cin >> n)
	{
    
    
		int ans = 0;
		while(n % 2 == 0)
		{
    
    
			n /= 2;
			ans++;
		}
		cout << ans << endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/113572465