191:位1的个数

This commit is contained in:
huangge1199@hotmail.com 2021-07-19 23:19:16 +08:00
parent e3685e9583
commit cd73435799
2 changed files with 140 additions and 0 deletions

View File

@ -0,0 +1,85 @@
//编写一个函数输入是一个无符号整数以二进制串的形式返回其二进制表达式中数字位数为 '1' 的个数也被称为汉明重量
//
//
//
// 提示
//
//
// 请注意在某些语言 Java没有无符号整数类型在这种情况下输入和输出都将被指定为有符号整数类型并且不应影响您的实现因为无论整数是有符号的
//还是无符号的其内部的二进制表示形式都是相同的
// Java 编译器使用二进制补码记法来表示有符号整数因此在上面的 示例 3 输入表示有符号整数 -3
//
//
//
//
// 示例 1
//
//
//输入00000000000000000000000000001011
//输出3
//解释输入的二进制串 00000000000000000000000000001011 共有三位为 '1'
//
//
// 示例 2
//
//
//输入00000000000000000000000010000000
//输出1
//解释输入的二进制串 00000000000000000000000010000000 共有一位为 '1'
//
//
// 示例 3
//
//
//输入11111111111111111111111111111101
//输出31
//解释输入的二进制串 11111111111111111111111111111101 共有 31 位为 '1'
//
//
//
// 提示
//
//
// 输入必须是长度为 32 二进制串
//
//
//
//
//
//
//
// 进阶
//
//
// 如果多次调用这个函数你将如何优化你的算法
//
// Related Topics 位运算
// 👍 364 👎 0
package leetcode.editor.cn;
//191:位1的个数
class NumberOf1Bits {
public static void main(String[] args) {
//测试代码
Solution solution = new NumberOf1Bits().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
if ((n & 1) == 1) {
count++;
}
n >>>= 1;
}
return count;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,55 @@
<p>编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为<a href="https://baike.baidu.com/item/%E6%B1%89%E6%98%8E%E9%87%8D%E9%87%8F" target="_blank">汉明重量</a>)。</p>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>请注意,在某些语言(如 Java没有无符号整数类型。在这种情况下输入和输出都将被指定为有符号整数类型并且不应影响您的实现因为无论整数是有符号的还是无符号的其内部的二进制表示形式都是相同的。</li>
<li>在 Java 中,编译器使用<a href="https://baike.baidu.com/item/二进制补码/5295284" target="_blank">二进制补码</a>记法来表示有符号整数。因此,在上面的 <strong>示例 3</strong> 中,输入表示有符号整数 <code>-3</code></li>
</ul>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>00000000000000000000000000001011
<strong>输出:</strong>3
<strong>解释:</strong>输入的二进制串 <code><strong>00000000000000000000000000001011</strong> 中,共有三位为 '1'。</code>
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>00000000000000000000000010000000
<strong>输出:</strong>1
<strong>解释:</strong>输入的二进制串 <strong>00000000000000000000000010000000</strong> 中,共有一位为 '1'。
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>11111111111111111111111111111101
<strong>输出:</strong>31
<strong>解释:</strong>输入的二进制串 <strong>11111111111111111111111111111101</strong> 中,共有 31 位为 '1'。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>输入必须是长度为 <code>32</code><strong>二进制串</strong></li>
</ul>
<ul>
</ul>
<p> </p>
<p><strong>进阶</strong></p>
<ul>
<li>如果多次调用这个函数,你将如何优化你的算法?</li>
</ul>
<div><div>Related Topics</div><div><li>位运算</li></div></div>\n<div><li>👍 364</li><li>👎 0</li></div>