g0101_0200.s0191_number_of_1_bits.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0101_0200.s0191_number_of_1_bits;
// #Easy #Top_Interview_Questions #Bit_Manipulation
public class Solution {
public int hammingWeight(int n) {
int sum = 0;
boolean flag = false;
if (n < 0) {
flag = true;
n = n - Integer.MIN_VALUE;
}
while (n > 0) {
int k = n % 2;
sum += k;
n /= 2;
}
return flag ? sum + 1 : sum;
}
}