HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Shift Operator Multiplier

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
shiftmultiplieroperator

Problem

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>= 1;  
            i++;
        }
        return s;
    }
}

Solution

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>= 1;  
        i++;
    }
    return s.toString();
}

Code Snippets

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();
}

Context

StackExchange Code Review Q#114451, answer score: 6

Revisions (0)

No revisions yet.