package math.calculate;
import java.util.Scanner;
public class testBitOperation {
private static Scanner scan;
public static void main(String[] args) {
// 位移运算
System.out.println(16 >> 2);// 4(右移两位),相当于除以2的2次(4) -- 16:0001 0000→0000
// 0100
System.out.println(5 << 3);// 40(左移三位),相当于乘以2的3次(8) -- 5: 0000 0101→0010
// 1000
System.out.println(Math.pow(2, 16));// 65536.0
System.out.println(65536 & (65536 - 1));// 0 -- 与运算
System.out.println(65536 | (65536 - 1));// 131071 -- 或运算
System.out.println("请输入数字:");
scan = new Scanner(System.in);
int read = scan.nextInt();
System.out.println("输入数据:" + read);
if ((read & (read - 1)) != 0) {
System.out.println("不是2的幂次方");
} else {
System.out.println(log2(read));// 16
}
System.out.println(Func3(8));
System.out.println(ifPower(65536,2));
}
static int log2(int value) // 递归判断一个数是2的多少次方
{
if (value == 1)
return 0;
else
return 1 + log2(value >> 1);
}
static int ifPower(int num, int base) {
if(num==1 || base==1){
return 0;
}
if(num%base!=0){
return 0;
}
return 1+ifPower(num/base,base);
}
static int Func3(int data) { // 利用了data&(data-1)每次都能移除最右边的1,移除了多少个1,就是包含了几个1
int count = 0;
while (data > 0) {
data = data & (data - 1);
count++;
}
return count;
}
}
求一个数是否是另一个数的n次方幂、一个数是否是2的n次方幂
本文转载:CSDN博客