http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3987
Test instructions
Given a number n, now to divide it into the number of M, the m number must be equal to N, and to make the m number or value of the smallest.
Ideas:
From the point of view of binary analysis, if there is a number in this m number of one is 1, then the last or up this bit is definitely 1, so if one is 1, then we try to let the rest of the bit also equals 1.
So we start with the highest bit enumeration to see if this bit needs to be 1, if it needs to be 1, then the remaining number will try to make this bit equal to 1.
1 Importjava.math.*;2 ImportJava.util.Scanner;3 4 Public classMain {5 Public Static voidMain (string[] args) {6 BigInteger N, m;7Scanner in =NewScanner (system.in);8 intT =in.nextint ();9 for(intcas=0;cas<t;cas++){Tenn =In.nextbiginteger (); Onem =In.nextbiginteger (); A intLen = 0; -BigInteger SS =N; - while(Ss.compareto (Biginteger.zero) >0){ theSS = Ss.divide (Biginteger.valueof (2)); -len++; - } - BigInteger tmp; +BigInteger ans =NewBigInteger ("0"); - for(inti = len; i>0; i--){ + if(N.compareto (Biginteger.zero) <=0) Break; ATMP = biginteger.valueof (2). POW (i-1). Subtract (biginteger.valueof (1)); atBigInteger sum =tmp.multiply (m); - if(Sum.compareto (n) <0){ -BigInteger num = N.divide (biginteger.valueof (2). POW (i-1)); - if(Num.compareto (m) >0) num =m; -n = n.subtract (biginteger.valueof (2). POW (i-1). Multiply (num)); -Ans = Ans.add (biginteger.valueof (2). POW (i-1)); in } - } to System.out.println (ans); + } - in.close (); the } *}
ZOJ 3987 Numbers (Java enumeration)