191. Number of 1 Bits Easy
1/**
2 * [191] Number of 1 Bits
3 *
4 * Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).
5 * Note:
6 *
7 * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
8 * In Java, the compiler represents the signed integers using <a href="https://en.wikipedia.org/wiki/Two%27s_complement" target="_blank">2's complement notation</a>. Therefore, in Example 3, the input represents the signed integer. -3.
9 *
10 *
11 * Example 1:
12 *
13 * Input: n = 00000000000000000000000000001011
14 * Output: 3
15 * Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
16 *
17 * Example 2:
18 *
19 * Input: n = 00000000000000000000000010000000
20 * Output: 1
21 * Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
22 *
23 * Example 3:
24 *
25 * Input: n = 11111111111111111111111111111101
26 * Output: 31
27 * Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
28 *
29 *
30 * Constraints:
31 *
32 * The input must be a binary string of length 32.
33 *
34 *
35 * Follow up: If this function is called many times, how would you optimize it?
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/number-of-1-bits/
40// discuss: https://leetcode.com/problems/number-of-1-bits/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45 pub fn hammingWeight (n: u32) -> i32 {
46 0
47 }
48}
49
50// submission codes end
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn test_191() {
58 }
59}
60
Back
© 2025 bowen.ge All Rights Reserved.