当前位置:网站首页>二进制中1的个数
二进制中1的个数
2022-08-02 03:33:00 【小艾菜菜菜】
题目描述:
给定一个长度为 n 的数列,求出数列中每个数的二进制表示中 1 的个数。
输入格式:
第一行包含整数 n。
第二行包含 n 个整数,表示整个数列。
输出格式:
共一行,包含 n 个整数,其中的第 i 个数表示数列中的第 i 个数的二进制表示中 1 的个数,
输入样例:
5
1 2 3 4 5
输出样例:
1 1 2 1 2
解题思路:
第一种:
使用最原始的求二进制的方式来统计数中 1 的个数
第二种:
通过使用 lowbit 函数来实现。
lowbit 函数的用处,它主要做的就是返回(原数 与上 原数的反) 之后的数,即返回该数的倒数第一个出现的1 ;
我们此时通过减去原数中的 1 的个数来进行统计。
代码实现:
第一种:
#include <iostream>
using namespace std;
const int N = 100010;
int a[N];
int count(int x)
{
int sum = 0;
while (x)
{
sum += x % 2;
x /= 2;
}
return sum;
}
int main()
{
int n ;
cin >> n;
int res = 0;
for (int i = 0; i < n; i++)
{
cin >> a[i];
res = count(a[i]);
cout << res << ' ';
}
return 0;
}
第二种:
#include <iostream>
using namespace std;
int lowbit(int x)
{
return x & -x; //返回 返回该数的倒数第一个出现的1
}
int main()
{
int n ;
scanf("%d",&n);
while (n --)
{
int res = 0; // 每对一个数把res清为0
int x ;
scanf("%d",&x);
while (x ) x -= lowbit(x),res ++;
cout << res << ' ';
}
return 0;
}
边栏推荐
猜你喜欢
随机推荐
【详解】线程池及其自定义线程池的实现
bluez5.50蓝牙文件传输
2020 - AAAI - Image Inpainting论文导读《Learning to Incorporate Structure Knowledge for Image Inpainting》
剑指Offer 31.栈的压入、弹出
发布全新的配置格式 - AT
【LeetCode】求和
HAL库笔记——通过按键来控制LED(基于正点原子STM32F103ZET6精英板)
Mac安装MySQL详细教程
MPU6050 accelerometer and gyroscope sensor is connected with the Arduino
笔记本电脑充电问题
谷粒商城10——搜索、商品详情、异步编排
使用pyqt弹出消息提示框
WebApp 在线编程成趋势:如何在 iPad、Matepad 上编程?
AD Actual Combat
MQ-5 combustible gas sensor interface with Arduino
Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development
TQP3M9009电路设计
倒排单词
分割回文串 DP+回溯 (LeetCode-131)
所有子字符串中的元音 —— LeetCode - 2063









