每日一题(小白)模拟娱乐篇13

今天题目比较简单,直接分析。小蓝想知道2024这个数字中有几个1,计算机组成学习好的同学肯定可以直接长除法或者瞪眼法得出答案:

2024=11111101000(B)也就是说2024中有一共有六个1

接下来用代码实现 ,我们也可以看出其中的有效数字为2,2,4;判断出2和4的二进制包含几个1就可以,先将数字转换为二进制,然后判断2024二进制包含几位1,输出即可。

代码实现👇

复制代码
		System.out.println(Integer.bitCount(2024));//瞪眼法

bitCount(int i) 函数,实现统计一个数的二进制位有多少个 1

复制代码
	public static void main(String[] args) {
		Scanner scanner =new Scanner(System.in);
		int i=2024;
		String binaryString = Integer.toBinaryString(i);
		int count=0;
		for (int j = 0; j < binaryString.length(); j++) {
			if (binaryString.charAt(j)=='1') {
				count++;
			}
		}
		System.out.println(count);
		
		scanner.close();
				
	}

转换法

复制代码
	public static void main(String[] args) {
		Scanner scanner =new Scanner(System.in);
		int i=2024;
		int count=0;
		while (i>0) {
			if (i%2!=0) {//二进制就是2的多少次方
				count++;
			}
			i/=2;
		}
		System.out.println(count);
				
	}

自己写方法

复制代码
	public static void main(String[] args) {
		Scanner scanner =new Scanner(System.in);
		int i=2024;
		int count=0;
		while (i>0) {
			count+=i%2;//与长除法类似,利用长除法的原理
			i/=2;
		}
		System.out.println(count);
				
	}
相关推荐
无风听海4 分钟前
C# 隐式转换深度解析
java·开发语言·c#
碧海银沙音频科技研究院6 分钟前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
一只大袋鼠1 小时前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作
java·开发语言·git
csdn_aspnet1 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
德思特2 小时前
从 Dify 配置页理解 RAG 的重要参数
java·人工智能·llm·dify·rag
YOU OU2 小时前
Spring IoC&DI
java·数据库·spring
один but you2 小时前
从可变参数到 emplace:现代 C++ 性能优化的核心组合
java·开发语言
是码龙不是码农3 小时前
ThreadPoolExecutor 7 个核心参数详解
java·线程池·threadpool
这是程序猿3 小时前
Spring Boot自动配置详解
java·大数据·前端