0
点赞
收藏
分享

微信扫一扫

【Kevin Learn 算法与数据结构】--> 《剑指 offer》 二进制中1的个数

yeamy 2022-06-22 阅读 23

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
题目链接:​​​牛客网​​

代码

方法一

public class Solution {
public int NumberOf1(int n) {
int cnt = 0;
while (n != 0) {
cnt++;
n &= (n - 1);
}
return cnt;
}
}

方法二

public class Solution {
public int NumberOf1(int n) {
return Integer.bitCount(n);
}
}

测试结果

【Kevin Learn 算法与数据结构】--> 《剑指 offer》 二进制中1的个数_补码


举报

相关推荐

0 条评论