본문 바로가기

Java 개념정리

[Java] int 값의 2진수 이진 표현에서 1비트 개수를 반환해주는 함수, Integer.bitcount()

int 값의 2진수 이진 표현에서 1비트 개수를 반환해주는 메소드, Integer.bitcount()

만약 숫자값의 이진수에서 "1"의 개수를 파악하고 싶다면, 해당 함수를 사용하면 된다.

Integer.bitCount(int i)는 숫자를 1차로 이진변환하고, 그 이후 이진변환된 값에서 "1"의 개수를 확인한다.

class Solution {
    public int solution(int n) {
        int bitCnt = Integer.bitCount(n);
        return bitCnt;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int n = 1; // 이진법 변환 : 1
        int n2 = 2; // 이진법 변환 : 10
        int n3 = 3; // 이진법 변환 : 11
        int n4 = 4; // 이진법 변환 : 100
        int n5 = 5; // 이진법 변환 : 101
        System.out.println(sol.solution(n)); // 출력 : 1
        System.out.println(sol.solution(n2)); // 출력 : 1
        System.out.println(sol.solution(n3)); // 출력 : 2
        System.out.println(sol.solution(n4)); // 출력 : 1
        System.out.println(sol.solution(n5)); // 출력 : 2

    }
}

→ 예시로 int값이 5라면, Integer.bitCount(n)은 1차로 int값을 이진 변환 해주므로 101이 되고,

이후 "1"의 개수를 세보면 두개가 나오기때문에 출력값이 2가 나오게 된다.

 


출처

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

 

Integer (Java Platform SE 7 )

Returns the value obtained by rotating the two's complement binary representation of the specified int value right by the specified number of bits. (Bits shifted out of the right hand, or low-order, side reenter on the left, or high-order.) Note that right

docs.oracle.com


Integer.bitCount() 활용문제

https://rimmee97.tistory.com/184

 

[프로그래머스] LV. 2 (다음 큰 숫자)(java)

[문제] → 숫자를 이진변환 한 후, 1의 개수를 세주는 함수 Integer.bitCount(int i) 를 사용하여 풀이 answer의 숫자는 n + 1로 잡아준다(다음 큰 숫자는 n보다 큰 자연수이므로) while문을 돌리면서 answer의 1

rimmee97.tistory.com