10
\$\begingroup\$

Please suggest a way to optimize the below code. I want to reduce the execution time. This is a program to multiply using the shift operator.

import java.util.Scanner;
public class Test2 {
 public static void main(String args[] ) throws Exception {
 Scanner in = new Scanner(System.in);
 int N = in.nextInt();
 long[] [] list=new long[N][2];
 for(int i=0;i<N;i++){
 list[i][0]=in.nextLong();
 list[i][1]=in.nextLong();
 }
 for(long[] s:list){
 System.out.println(calc(s[0], s[1]));
 }
 }
 public static String calc(long n1, long n2) {
 long temp, i = 0, result = 0;
 String s=null;
 while (n2 != 0) {
 if ((n2 & 1) == 1) {
 temp = n1;
 if(s==null){
 s="("+i+"-"+i+") ";
 }else{
 s=s+"("+i+"-"+i+") + ";
 }
 result += (temp<<=i); 
 }
 n2 >>= 1; 
 i++;
 }
 return s;
 }
}
TheCoffeeCup
9,5164 gold badges38 silver badges96 bronze badges
asked Dec 19, 2015 at 14:56
\$\endgroup\$
3
  • \$\begingroup\$ I changed the title to state what the code does to better follow site rules, and cleaned up a couple other minor issues. I hope you get a good answer. \$\endgroup\$ Commented Dec 19, 2015 at 15:01
  • \$\begingroup\$ can you expand a little bit on how your program works, exactly? If I input the numbers 4 and 3, I get (0-0) (1-1) + . If I input 2 and 3, I get the same result. If I input 1001 and 0110, I get (3-3) (6-6) + , which is also what I get with 101 and 0110. I'm quite unsure what is expected as input, and what is delivered as output. \$\endgroup\$ Commented Dec 20, 2015 at 21:03
  • \$\begingroup\$ @tim sorry for let reply here main thing is result that is multiplication of two number using shift operator,I was printing value of i just for convenience to see how loop is running . \$\endgroup\$ Commented Dec 27, 2015 at 16:00

1 Answer 1

6
\$\begingroup\$

The first thing I see is concatenating a string in a loop. This will create a new string every loop. You don't want that.

Instead use a StringBuilder:

public static String calc(long n1, long n2) {
 long temp, i = 0, result = 0;
 StringBuilder s=new StringBuilder();
 while (n2 != 0) {
 if ((n2 & 1) == 1) {
 temp = n1;
 if(s.length()!=0)s.append("+ ");
 s.append("(").append(i).append("-").append(i).append(") ");
 result += (temp<<=i); 
 }
 n2 >>= 1; 
 i++;
 }
 return s.toString();
}
answered Dec 19, 2015 at 16:35
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.