Java实现 蓝桥杯 算法训练 乘法次数

乘法次数

资源限制
时间限制:1.0s 内存限制:999.4MB
问题描述
  给你一个非零整数,让你求这个数的n次方,每次相乘的结果可以在后面使用,求至少需要多少次乘。如24:22=22(第一次乘),2222=24(第二次乘),所以最少共2次;
输入格式
  第一行m表示有m(1<=m<=100)组测试数据;
  每一组测试数据有一整数n(0<n<=100000000);
输出格式
  输出每组测试数据所需次数s;
样例输入
3
2
3
4
样例输出
1
2
2

PS:
二分法

import java.util.ArrayList;
import java.util.Scanner;

public class 乘法次数 {
	public static void main(String[] args) {
		ArrayList<Integer> input = new ArrayList<Integer>();
		ArrayList<Integer> result = new ArrayList<Integer>();
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		for (int i = 0; i <n; i++) {
			input.add(sc.nextInt());
		}
		for(int i:input){
			int temp=0;
			while(i!=1){
				if(i%2==0){
					temp+=1;
				}
				else{
					temp+=2;
				}
				i/=2;
			}
			result.add(temp);
		}
		for (int i:result) {
			System.out.println(i);
		}
	}

}

  • 20
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 28
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 28
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值