算法练习-给一个正整数n,计算它最多能被2的多少次幂整除

给一个正整数n,计算它最多能被2的多少次幂整除

题目来自51nod, 原文链接

题目分析

输入:正整数n
输出:2的k次幂
根据题目,我们只需要从0次开始,循环每次K+1,直到2的k次幂大于正整数n跳出循环。

解法1

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int fun(int n) {
	int k = 0, index = 0, sum = 0;
	while (n > sum) {
		sum = pow(2, index);
		if (n%sum == 0) {
			k = index;
		}
		index++;
	}
	return k;
}

int main() {
	int n;
	scanf("%d", &n);
	printf("%d", fun(n));

	system("pause");
	return 0;
}

解法2

以上是我做题的思路,提交完代码后发现还有另外的写法,代码更简洁,贴在这里学习一下。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main() {
	int n, k = 0;
	scanf("%d", &n);
	while (n % 2 == 0) {
		n = n / 2;
		k++;
	}
	printf("%d", k);
	system("pause");
	return 0;
}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值