当前位置:网站首页>二进制序列
二进制序列
2022-07-30 22:17:00 【@Main.】
目录
题一:找出二进制序列中数字1的个数
方法一:目标数字向右移,一直移到最高位
public class Test {
public static void main1(String[] args) {
int num = 7;
int count = 0;
int n = 0;
while(n < 32){
if(((num >> n) & 1) == 1){
count++;
}
n++;
}
System.out.println(count);
}
}
方法二:目标数字向右移,一直移到无效位
解法与方法一一致,但方法一对于任何数都要右移32位,效率较低,方法二可以只计算有效位。
public class Test {
public static void main2(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
int num = sc.nextInt();
int count = 0;
while(num != 0){
if((num & 1) != 0){
count++;
}
num = num >> 1;
}
System.out.println(count);
}
sc.close();
}
}
方法三:相邻数字按位与,一直算到为 0 止
一直和相邻的数字运算,最终会得到0,算了几次就有几个1。
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
int num = sc.nextInt();
int count = 0;
while(num != 0){
num = num & (num - 1);
count++;
}
System.out.println(count);
}
sc.close();
}
}
题二:输出二进制序列中偶数位与奇数位
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =0;
while(sc.hasNextInt()){
int num = sc.nextInt();
//偶数位
System.out.print("偶数位:");
for (n = 30; n >= 0; n -= 2) {
System.out.print((num >> n) & 1);
}
System.out.println();
//奇数位
System.out.print("奇数位:");
for (n = 31; n >= 1 ; n-= 2) {
System.out.print((num >> n) & 1);
}
System.out.println();
}
}
边栏推荐
猜你喜欢
MySql创建数据表
解决centos8 MySQL密码问题ERROR 1820 (HY000) You must reset your password using ALTER USER
MySQL user authorization
Navicat cannot connect to mysql super detailed processing method
鳄梨价格数据集(Avocado Prices)
Py之pdpbox:pdpbox的简介、安装、案例应用之详细攻略
Ningbo Zhongning Pawn will transfer 29.5% of the equity for 2.8338 million yuan, and the owner's equity in 2021 will be 9.6875 million yuan
482-静态库、动态库的制作、使用及区别
代码越写越乱?那是因为你没用责任链
史上最全的Redis基础+进阶项目实战总结笔记
随机推荐
JUC原子类详解
Solve npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead
Navicat new database
Difference between cookie and session
Jetson AGX Orin 平台关于c240000 I2C总线和GMSL ses地址冲突问题
MySQL 用户授权
MySQL 8.0.29 设置和修改默认密码
Learning about XML (1)
【微信小程序】小程序突破小程序二维码数量限制
mysql创建表
PhpMetrics 使用
matlab标量场作图
Golang go-redis cluster模式下不断创建新连接,效率下降问题解决
ValueError: Append mode is not supported with xlsxwriter解决方案
TCP 连接 三次握手 四次挥手
MySQL压缩包方式安装,傻瓜式教学
The most powerful and most commonly used SQL statements in history
HCIP第十六天
成功解决ModuleNotFoundError: No module named ‘Image‘
3 minutes to take you to understand WeChat applet development