LeetCode - 191. Number of 1 Bits(Bit Manipulation)*

YAMAMAMO·2022년 3월 8일
0

LeetCode

목록 보기
39/100

문제

부호 없는 정수를 가져다가 이 값이 갖는 '1'비트 수(해밍 가중치라고도 함)를 반환하는 함수를 작성합니다.
참고:
Java와 같은 일부 언어에는 부호 없는 정수 유형이 없습니다. 이 경우 입력은 부호 있는 정수 형식으로 제공됩니다. 정수의 내부 이진 표현은 서명 여부와 상관없이 동일하므로 구현에 영향을 미치지 않아야 합니다.
자바에서 컴파일러는 2의 보완 표기법을 사용하여 부호 있는 정수를 나타낸다. 따라서 예제 3에서 입력은 부호 있는 정수를 나타냅니다. .-3

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

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Note:
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.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. .-3

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Constraints:

The input must be a binary string of length .32

풀이

자바입니다.

비트연산자 사용

  • & 은 비트가 같으면 1, 다르면 0
  • (n>>>1) 1칸 이동 - ex) 11111000 -> 01111100
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
  	 	int res = 0;
    	while(n!=0) {
    		res += (n & 1);
    		n = n>>>1;
    	}
    	return res;
        
    }
}

Integer.bitCount() 사용

  • int가 이진수일때 1 의 개수를 반환합니다.
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
  
    	return Integer.bitCount(n);
        
    }
}
profile
안드로이드 개발자

0개의 댓글