【位运算】移位操作实现乘法运算
1 import java.util.Scanner; 2 3 /** 4 * 功能:用位运算,实现乘法运算,但仅限于乘数是偶数。 5 */ 6 public class Main2 { 7 8 public int powerN(int m, int n) { 9 while (n > 0) { 10 m = m << 1; 11 n--; 12 } 13 return m; 14 } 15 16 public static void main(String[] args) { 17 18 Main2 main2 = new Main2(); 19 Scanner scanner = new Scanner(System.in); 20 21 int input = 0; 22 int n = 0; 23 24 while (scanner.hasNext()) { 25 input = scanner.nextInt(); 26 27 if (input == 0 || input % 2 == 1) { 28 System.out.println("the intput value is invalid!"); 29 continue; 30 } 31 32 n = 0; 33 34 while (input != 1) { 35 n++; 36 input = input / 2; 37 } 38 39 System.out.println(main2.powerN(2, n)); 40 } 41 } 42 }