Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int hammingWeight(int n) {
- // Binary numbers are not really different
- // from decimal numbers that we usually use.
- // In decimal representation (base 10),
- // we have 10 digits (0, 1, 2, ..., 8, 9).
- // If we start counting from 1, we have:
- // 1 (which we can also write as 00001)
- // 2 (which we can also write as 00002)
- // 3 (which we can also write as 00003)
- // ....
- // 9 (which we can also write as 00009)
- // 10 (which we can also write as 00010)
- // ....
- // 99 (which we can also write as 00099)
- // 100 (which we can also write as 00100)
- // ....
- // 999 (which we can also write as 00999)
- // 1000 (which we can also write as 01000)
- // ....
- // In decimal representation, if we want to
- // add a 0 at the end of the number, we
- // multiply it by 10 (since it's base 10 numbers).
- // In binary representation (base 2),
- // we have just 2 digits (0 and 1).
- // If we start counting from 1, we have:
- // 1 is 00001 in binary representation.
- // 2 is 00010 in binary repr.
- // 3 is 00011 in binary repr.
- // 4 is 00100 in binary repr.
- // 5 is 00101 in binary repr.
- // 6 is 00110 in binary repr.
- // 7 is 00111 in binary repr.
- // 8 is 01000 in binary repr.
- // 9 is 01001 in binary repr.
- // 10 is 01010 in binary repr.
- // 11 is 01011 in binary repr.
- // In binary representation, if we want to
- // add a 0 at the end of the number, we
- // multiply it by 2 (since it's base 2 numbers).
- // << is called a binary left-shift
- // or just a left-shift operation.
- // It is essentially adding a specified # of 0s
- // at the end (in binary repr.),
- // i.e. multiply by 2 specified number of times.
- int one = 1 << 0; // binary repr: 00001
- int two = 1 << 1; // binary repr: 00010
- int four = 1 << 2; // binary repr: 00100
- // etc.
- // int is a 32-bit type, so it has bits 0-31.
- // 31st bit is responsible for non-negative/negative notion.
- // Since n is positive, we are only interested in bits
- // 0-30.
- // n = 11 00000000000000000000000001011 n
- // 00000000000000000000000000001 bitmask
- // 00000000000000000000000000001 n & bitmask
- // n = 11 00000000000000000000000001011 n
- // 00000000000000000000000000010 bitmask
- // 00000000000000000000000000010 n & bitmask
- // n = 11 00000000000000000000000001011 n
- // 00000000000000000000000000100 bitmask
- // 00000000000000000000000000000 n & bitmask
- // n = 11 00000000000000000000000001011 n
- // 00000000000000000000000001000 bitmask
- // 00000000000000000000000001000 n & bitmask
- int answer = 0;
- for (int i = 0; i <= 30; i++) {
- // i = 0, 000000000000001
- // i = 1, 000000000000010
- // i = 2, 000000000000100
- // i = 3, 000000000001000
- // ...
- int bitmask = 1 << i;
- if ((n & bitmask) > 0) {
- answer++;
- }
- }
- return answer;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement