365体育网页版在线登录官网-365平台被黑不给出款怎么办-beat365为什么登录不了

深度阅读体验

365平台被黑不给出款怎么办

牛客题解 | 二进制中有多少个1

题目 题目链接 解题思路 计算32位整数二进制表示中1的个数,有几种常用方法: 位运算法: 使用 \(\text{n} \& \text{1}\) 判断最低位是否为1 右移 \(\

牛客题解 | 二进制中有多少个1

题目

题目链接

解题思路

计算32位整数二进制表示中1的个数,有几种常用方法:

位运算法:

使用 \(\text{n} \& \text{1}\) 判断最低位是否为1

右移 \(\text{n}\),继续判断

统计所有为1的位

n & (n-1) 法:

每次操作会消除最右边的1

统计操作次数即为1的个数

这种方法更高效,因为只需要处理1的个数次

查表法:

预处理所有8位数的1的个数

将32位数分成4个8位处理

适合处理大量数据

代码

#include

using namespace std;

class Solution {

public:

// 方法1:位运算统计

int countOnes1(int n) {

int count = 0;

while (n) {

count += n & 1;

n >>= 1;

}

return count;

}

// 方法2:n & (n-1)

int countOnes2(int n) {

int count = 0;

while (n) {

n &= (n - 1);

count++;

}

return count;

}

};

int main() {

int n;

cin >> n;

Solution solution;

cout << solution.countOnes2(n) << endl;

return 0;

}

import java.util.*;

public class Main {

static class Solution {

// 方法1:位运算统计

public int countOnes1(int n) {

int count = 0;

while (n != 0) {

count += n & 1;

n >>>= 1; // 使用无符号右移

}

return count;

}

// 方法2:n & (n-1)

public int countOnes2(int n) {

int count = 0;

while (n != 0) {

n &= (n - 1);

count++;

}

return count;

}

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

Solution solution = new Solution();

System.out.println(solution.countOnes2(n));

}

}

def count_ones_1(n: int) -> int:

"""方法1:位运算统计"""

count = 0

while n:

count += n & 1

n >>= 1

return count

def count_ones_2(n: int) -> int:

"""方法2:n & (n-1)"""

count = 0

while n:

n &= (n - 1)

count += 1

return count

if __name__ == "__main__":

n = int(input())

print(count_ones_2(n))

算法及复杂度

算法:位运算

时间复杂度:

方法1:\(\mathcal{O}(32)\) = \(\mathcal{O}(1)\)

方法2:\(\mathcal{O}(k)\),\(k\) 为1的个数

空间复杂度:\(\mathcal{O}(1)\)

相关阅读

beat365为什么登录不了 命理八字什么叫暗合(简单说说八字中的暗合)

命理八字什么叫暗合(简单说说八字中的暗合)

1、干支暗合涉及通禄合与余刃合。通禄合如甲午中的甲与己暗合,天干与地支的先天五行关系在特定位置得到体现。余刃合则仅限于丙戌与庚辰