본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1356. Sort Integers by The Number of 1 Bits

반응형

https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

bitmasking을 이용한 문제였습니다.

📕 풀이방법

📔 풀이과정

1. arr을 정렬할 때 기준을 정해 sort해줍니다. 정렬 기준은 다음과 같습니다.

1 bit 개수가 같다면 오름차순으로, 다르면 bit개수의 오름차순으로 sort해줍니다.

2. bit개수를 세는 함수 bits를 구현해줍니다.

방법은 어떤 수 n의 가장 오른쪽 bit & 1의 결과를 세주는 것입니다. 세준 후에는 오른쪽으로 bit를 밀어줍니다.

📔 정답 출력 | 반환

arr를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    static int bits(int n) {
        int cnt = 0;
        while(n) {
            cnt += n & 1;
            n >>= 1;
        }
        return cnt;
    }

    static bool cmp (int &a, int &b) {
        int aBits = bits(a);
        int bBits = bits(b);
        if(aBits == bBits) return a < b;
        return aBits < bBits;
    }

    vector<int> sortByBits(vector<int>& arr) {
        sort(arr.begin(), arr.end(), cmp);
        return arr;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.