[코테 풀이] Number of 1 Bits

시내·2024년 7월 26일
0

Q_191) Number of 1 Bits

출처 : https://leetcode.com/problems/number-of-1-bits/

Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).

class Solution {
    public int hammingWeight(int n) {
        int count =0;
        String bin = Integer.toBinaryString(n);
        for (int i = 0; i < bin.length(); i++) {
            if(bin.charAt(i)=='1') count++;
        }
        return count;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글