+ 5

Java question

Hello, Im learning java and im currently writing a program that multiplies a number from the user (6) and multiplies that number with 23. The thing is that i am not allowed to use the * operator and NO loops, just the leftshift operator (<<). The problem is 23*6=138, but it gives me a different number. Here is the code i tried: import java.util.Scanner; public class Multiplication { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Multiply N by 23"); //23*6=138 System.out.print("Input N: "); int N = scan.nextInt(); //6 = 0110 int Z = 23; // 0001 0111 int result; if(N==0) result=0; else result= (16<<N)+(4<<N)+(2<<N)+N; //System.out.println("23*"+N+ "= "+ (Z<<2)); //System.out.println((16<<N)+(4<<N)+(2<<N)+N); System.out.println(result); } }

20th Feb 2019, 6:43 PM
Camilo Espinosa
Camilo Espinosa - avatar
2 Antworten
+ 5
https://code.sololearn.com/cS1ymlI3Lkg8/?ref=app Hope this helps to understand how the left shift works and how you can use it for multiplication.
20th Feb 2019, 9:03 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
OK so first think about what kind of transformation is done by the leftshift. Start with 6 = 0110 Left shift by one binary digit: 6 << 1 = 1100 which is 12 (8*1 + 4*1 + 2*0 + 1*0) (so, the number you want to transform, is on the left side of the operator, and the number of shifts is on the right side). In more generalized form, left shifting the number N by S binary digits is equivalent to: N * 2^S So you want to multiply any input value (N) with 23 then you can express this so: N * 23 = N * (16 + 4 + 2 + 1) = N * (2^4 + 2^2 + 2^1 + 2^0) From here it should be clear how many left shifts can solve the problem, I hope you can apply it to your code!
20th Feb 2019, 7:38 PM
Tibor Santa
Tibor Santa - avatar