Shift Operator Multiplier 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&lt;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 &amp; 1) == 1) {
                temp = n1;
                if(s==null){
                    s="("+i+"-"+i+") ";
                }else{
                    s=s+"("+i+"-"+i+") + ";
                }
                result += (temp&lt;&lt;=i); 
            }
            n2 &gt;&gt;= 1;  
            i++;
        }
        return s;
    }
}
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 &amp; 1) == 1) {
            temp = n1;
            if(s.length()!=0)s.append("+ ");
            s.append("(").append(i).append("-").append(i).append(") ");
            result += (temp&lt;&lt;=i); 
        }
        n2 &gt;&gt;= 1;  
        i++;
    }
    return s.toString();
}