使用移位运算符做乘除法运算

一个整数每次执行移位运算中的左运算n次,相当于这个整数乘以2的n次方;

一个整数每次执行移位运算中的右运算n次,相当于这个整数除以2的n次方;

不过这种方式只能用于乘以除以2的n次方,但是他的效率比乘法运算要高;

public class Main {
	public static void main(String[] args) {
		int a = 0;
		a = 3 << 1;  
		System.out.println("3 << 1 = "+a+" (相当于3*2)");
		a = 3 << 2;   
		System.out.println("3 << 2 = "+a+" (相当于3*4)");
		int b = 0;
		b = 10 >> 1;  
		System.out.println("10 >> 1 = "+b+" (相当于10/2)");
		b = 10 >> 2;  
		System.out.println("10 >> 2 = "+b+" (相当于10/4)");
		
	}
}

运算结果:

猜你喜欢

转载自blog.csdn.net/asc_123456/article/details/82831169