Sort Integers by The Number of 1 Bits - LeetCode
Can you solve this real interview question? Sort Integers by The Number of 1 Bits - You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integ
leetcode.com
문제
You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the array after sorting it.
Example 1:
Input: arr = [0,1,2,3,4,5,6,7,8]
Output: [0,1,2,4,8,3,5,6,7]
Explantion: [0] is the only integer with 0 bits.
[1,2,4,8] all have 1 bit.
[3,5,6] have 2 bits.
[7] has 3 bits.
The sorted array by bits is [0,1,2,4,8,3,5,6,7]
Example 2:
Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]
Output: [1,2,4,8,16,32,64,128,256,512,1024]
Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.
Constraints:
- 1 <= arr.length <= 500
- 0 <= arr[i] <= 104
풀이
나의 풀이법
풀이 접근 과정
그냥 비트의 개수를 구하는 것만 알면 되겠다 싶었다.
kotlin으로 검색할 때는 안나왔는데 Java로 검색하니 바로 Integer.bitCount가 나왔고
이를 이용해 다중 정렬 연산자인 sortedWith와 compareBy를 이용하여 해결하였다.
최종 소스코드
class Solution {
fun sortByBits(arr: IntArray) =
arr.sortedWith(compareBy({ Integer.bitCount(it) }, { it }))
}
'LeetCode > Kotlin | Easy' 카테고리의 다른 글
[LeetCode/Kotlin]Easy - 392. Is Subsequence (0) | 2023.07.07 |
---|---|
[LeetCode/Kotlin]Easy - 58. Length of Last Word (0) | 2023.06.30 |
[LeetCode/Kotlin]Easy - 28. Find the Index of the First Occurrence in a String (0) | 2023.06.30 |
[LeetCode/Kotlin]Easy - 219. Contains Duplicate II (0) | 2023.06.30 |
[LeetCode/Kotlin]Easy - 136. Single Number (0) | 2023.06.30 |