File tree Expand file tree Collapse file tree
leetcode/src/main/java/com/fuyd/other Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .fuyd .other ;
2+
3+ /**
4+ * 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
5+ *
6+ *
7+ *
8+ * 示例 1:
9+ *
10+ * 输入:00000000000000000000000000001011
11+ * 输出:3
12+ * 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
13+ * 示例 2:
14+ *
15+ * 输入:00000000000000000000000010000000
16+ * 输出:1
17+ * 解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
18+ * 示例 3:
19+ *
20+ * 输入:11111111111111111111111111111101
21+ * 输出:31
22+ * 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
23+ *
24+ *
25+ * 提示:
26+ *
27+ * 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
28+ * 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
29+ *
30+ *
31+ * 进阶:
32+ * 如果多次调用这个函数,你将如何优化你的算法?
33+ *
34+ * 来源:力扣(LeetCode)
35+ * 链接:https://leetcode-cn.com/problems/number-of-1-bits
36+ * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
37+ *
38+ * @author fuyongde
39+ * @date 2020/2/17
40+ */
41+ public class Solution191 {
42+
43+ /**
44+ * 由于 int 占4字节(32位),故迭代32次即可
45+ * 时间复杂度:O(1)
46+ * 空间复杂度:O(1)
47+ */
48+ public int hammingWeight (int n ) {
49+ int bits = 0 , mask = 1 ;
50+ for (int i = 0 ; i < 32 ; i ++) {
51+ if ((n & mask ) != 0 ) {
52+ bits ++;
53+ }
54+ mask <<= 1 ;
55+ }
56+ return bits ;
57+ }
58+ }
You can’t perform that action at this time.
0 commit comments