[英]Multiplying Using Bitwise Shift Operators Giving TLE
Given N and M , write an equation using left shift operators whose result will be equal to the product N * M .
给定N和M ,使用左移位运算符编写一个方程,其结果将等于乘积N * M。
Input : First line has 0 < T ≤ 50000 denoting number of test cases.
输入:第一线具有0 <T≤50000表示的测试案例数量。
Next T lines have two integers 0 < N, M ≤ 10¹⁶.接下来的T行具有两个整数0 < N, M≤10 10。
Output : For each test case print an equation for N * M resembling
输出:为每个测试用例打印一个类似N * M的方程式
(N << p1) + (N << p2)+ ...+(N << pk) where p1 ≥ p2 ≥ ... ≥ pk and k is minimum.
(N << p1)+(N << p2)+ ... +(N << pk)其中p1≥p2≥...≥pk , k最小。
SAMPLE INPUT SAMPLE OUTPUT 2 2 1 (2<<0) 2 3 (2<<1) + (2<<0)
Time Limit: 1.0 sec
时限:1.0秒
My Solution 1st approach 我的解决方案第一种方法
int dig = (int)(Math.floor(Math.log10(m)/Math.log10(2))+1);
boolean flag = false;
for(long i = dig; i>=0; --i) {
if(((m>>(i-1l)) & 1l) == 1l) {
if(flag)
System.out.print(" + ("+n+ "<<"+(i-1)+")");
else {
System.out.print("("+n+"<<"+(i-1)+")");
flag = true;
}
}
}
Second Approach 第二种方法
boolean[] arr = new boolean[dig];
int i = dig-1;
while(m > 0) {
if((m&1) == 1 ) {
arr[i] = true;
}
i--;
m = m>>1l;
}
int j = dig-1;
for( i = 0; i < dig; ++i) {
if(arr[i]) {
if(flag)
System.out.print(" + ("+n+"<<"+j+")");
else {
System.out.print("("+n+"<<"+j+")");
flag = true;
}
}
j--;
}
In both cases I am getting 5 correct out of 8 and rest 3 are TLE why? 在这两种情况下,我都得到8分中的5分正确,其余3分是TLE为什么?
I don't actually see anything in both of your approaches preventing some ten-thousands of products of numbers up to 57 bit to be represented as String
s in one second: 在这两种方法中,我实际上都看不到任何东西能阻止一万个乘积高达57位的数字在一秒钟内表示为
String
:
TLE
may be due to System.out.print()
taking an inordinate amount of time. TLE
可能是由于System.out.print()
花费了过多的时间。
That said, use a utility like 也就是说,使用类似
/** builds <code>n * m</code> in the form
* <code>(n<<p1) + (n<<p2) + ... + (n<<pk)</code>
* using left shift.
* @param n (0 < multiplicand <= 10**16)
* @param m 0 < multiplier <= 10**16
* @return a verbose <code>String</code> for <code>n * m</code>
*/
static String verboseBinaryProduct(Object n, long m) {
int shift = Long.SIZE - Long.numberOfLeadingZeros(m) - 1;
final long highest = 1 << shift;
final StringBuilder binary = new StringBuilder(42);
final String chatter = ") + (" + n + "<<";
final long rest = highest - 1;
while (true) {
if (0 != (highest & m))
binary.append(chatter).append(shift);
if (0 == (rest & m)) {
binary.append(')');
return binary.substring(4);
}
m <<= 1;
shift -= 1;
}
}
and System.out.println(verboseBinaryProduct(n, m));
和
System.out.println(verboseBinaryProduct(n, m));
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.