Problem A A multiply B

 

 

/*ProblemA A multiply B
Time limit: 3 seconds
On currently available processors, a bit-wise shift instruction is faster than a multiply instruction
在当前可用的处理器上,逐位移位指令比乘法指令更快。
and can be used to multiply(shift left)and divide(Sshift right) by powers of two. 
可以用它乘以(左移)和除以(右移)2的幂。
In the case that only binary shift left operation, addition and subtraction are available, multiplication can be implemented in
只有二进制左移运算,加减法可用的情况下,乘法可以以多种方式实现。
various way.You are to figure out the minimum total number of times that addition or subtraction be used for multiply the given integers a and b.
你要算出用加法或减法乘以给定整数a和b的最小总次数
Input
The first line is a number T(I<T<100,000), represents the number of case. The next Tlines
follow each indicates a case. Each line contains two integers a and b.(1<a,b<231-1)。
第一行是数字T(1<T<100,000),表示大小写的数量,下一行包含两个整数 a和b.
Output
For each test case, you should print one integer indicates the answer. 
对于每个测试用例,你应该打印一个整数来表示答案。
*/
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] arr = new int[n][2];
        for(int i=0;i<n;i++){
            arr[i][0] = sc.nextInt();
            arr[i][1] = sc.nextInt();
        }
        for(int[] x:arr){
            System.out.println(Math.min(f(x[0]),f(x[1])));
        }
    }

    public static int f(int s){
        int cops = cops(s);
        int apws1 ,apws2;
        //如果这个数是2的N次幂 返回O
        if(cops==-1){
            return 0;
        }else{
            //如果不是 继续分解向前 向后分解此数
             apws1 = f((int) Math.pow(2, cops) - s);
             apws2 = f(s-(int) Math.pow(2, cops-1));
        }
        //返回最少运算符的值
        return apws1<apws2?apws1+1:apws2+1;
    }

    //返回-1的话 就为2的n次幂
    //返回为一个整形的话 就返回二进制的长度
    public static int cops(int s) {
        //list添加二进制数值
        List<Integer> list = new LinkedList<>();
        while (s > 0) {
            ((LinkedList<Integer>) list).addFirst(s % 2);
            s /= 2;
        }
            if (list.size() > 1) {
                int i=1;
            while (i<list.size()){
                if(list.get(i++)!=0){
                    return list.size();
                }
            }
        }
        return -1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值