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;
    }
}
发布了17 篇原创文章 · 获赞 26 · 访问量 7444

猜你喜欢

转载自blog.csdn.net/qq_41629684/article/details/89525985