当前位置:网站首页>二进制序列
二进制序列
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();
}
}
边栏推荐
猜你喜欢
史上最全的Redis基础+进阶项目实战总结笔记
ML之shap:基于FIFA 2018 Statistics(2018年俄罗斯世界杯足球赛)球队比赛之星分类预测数据集利用RF随机森林+计算SHAP值单样本力图/依赖关系贡献图可视化实现可解释性之攻略
Golang go-redis cluster模式下不断创建新连接,效率下降问题解决
matlab标量场作图
navicat无法连接mysql超详细处理方法
Uni-app 小程序 App 的广告变现之路:激励视频广告
IDEA2021.2安装与配置(持续更新)
About the data synchronization delay of MySQL master-slave replication
Advanced c language: pointers (5)
鳄梨价格数据集(Avocado Prices)
随机推荐
navicat新建数据库
Detailed explanation of the delete problem of ClickHouse delete data
proxy反向代理
The Road to Ad Monetization for Uni-app Mini Program Apps: Rewarded Video Ads
ThinkPHP high imitation blue play cloud network disk system source code / docking easy payment system program
@RequestBody、 @RequestParam 、 @PathVariable 和 @Vaild 注解
Advanced c language: pointers (5)
Navigation Bar----Personal Center Dropdown
Uni-app 小程序 App 的广告变现之路:激励视频广告
3 minutes to take you to understand WeChat applet development
MySQL cursors
WSL安装图形界面并通过xrdp/X-Launch访问
折叠旧版应用程序
系统结构考点之并行主存
Union, the difference between union and structure, the knowledge of enumeration of C language corners
【Network Security Column Directory】--Penguin Column Navigation
LeetCode·Daily Question·952. Calculate Maximum Component Size by Common Factor·Union Check
2sk2225 Substitute 3A/1500V Chinese Documentation【PDF Data Book】
系统结构考点之PM2I单级网络
MySQL compressed package installation, fool teaching