[Easy] 191. Number of 1Bits (Java)
https://leetcode.com/problems/number-of-1-bits/
Number of 1 Bits - LeetCode
Can you solve this real interview question? Number of 1 Bits - Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight [http://en.wikipedia.org/wiki/Hamming_w
leetcode.com
음주 이슈,,,
※ Question Summary
▶ Given an unsigned integer and return the number of '1' bits it has (known as the Hamming weight)
▶ Use integer as unsigned integer since there is no unsigned integer in Java
▶ Input : Unsigned integer n
▶ Output : Return the number of '1'bits it has
◈ Constraints
- The input must be a binary string of length 32.
◈ Input - 1
00000000000000000000000000001011
◈ Output - 1
3
◈ Input - 2
00000000000000000000000010000000
◈ Output - 2
1
◈ Input - 3
11111111111111111111111111111101
◈ Output - 3
31
◎ HOW TO SOLVE IT
▶ An unsigned integer has 4 bytes, which means it needs to be checked for 32 bits
▶ Check 'n & 1' 32 times, and each time after checking, shift 'n' to the right by 1 bit
▶ return the count of 1bits
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int nCount = 0;
for(int i = 0; i < 32; i++) {
int nBit = n & 1;
if(nBit == 1)
nCount++;
n = n >> 1;
}
return nCount;
}
}
I HOPE YOUR DAY GOES WELL :)