求一个数是否是另一个数的n次方幂、一个数是否是2的n次方幂

本文介绍了Java中位运算的基本概念及其应用场景,包括位移运算、按位与、按位或等操作,并通过实例展示了如何判断一个数是否为2的幂次方。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值