当前位置:网站首页>二进制中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;
}
边栏推荐
猜你喜欢
随机推荐
2020 - AAAI - 图像修复 Image Inpainting论文导读 -《Region Normalization for Image Inpainting》
Kinematics Analysis of Robot Arm
【LeetCode】Merge
使用飞凌嵌入式IMX6UL-C1板子——qt+opencv环境搭建
最第k大的数的一般性问题
Flame sensor connected with Arduino
Type c PD 电路设计
机械臂运动学解析
proteus数字电路仿真——入门实例
蛮力法求解凸包问题
IoT solution
【详解】优先级队列的底层实现
谷粒商城10——搜索、商品详情、异步编排
Mac安装MySQL详细教程
WebApp 在线编程成趋势:如何在 iPad、Matepad 上编程?
MIPI解决方案 ICN6202:MIPI DSI转LVDS转换芯片
Lightly 支持 Markdown 文件在线编写(文中提供详细 Markdown 语法)
剑指Offer 31.栈的压入、弹出
IDEA2021.2安装与配置(持续更新)
path 修补文件命令