diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README.md b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README.md index d5408ae9809d9..d76480bf8b462 100644 --- a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README.md +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README.md @@ -71,7 +71,10 @@ ```python - +class Solution: + def sortByBits(self, arr: List[int]) -> List[int]: + arr.sort(key=lambda x: (bin(x).count("1"), x)) + return arr ``` ### **Java** @@ -79,7 +82,19 @@ ```java - +class Solution { + public int[] sortByBits(int[] arr) { + int n = arr.length; + for (int i = 0; i < n; i++) { + arr[i] += Integer.bitCount(arr[i]) * 100000; + } + Arrays.sort(arr); + for (int i = 0; i < n; i++) { + arr[i] %= 100000; + } + return arr; + } +} ``` ### **...** diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md index 47f4e416d0c6b..aa9a8e6cec868 100644 --- a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md @@ -66,13 +66,28 @@ The sorted array by bits is [0,1,2,4,8,3,5,6,7] ### **Python3** ```python - +class Solution: + def sortByBits(self, arr: List[int]) -> List[int]: + arr.sort(key=lambda x: (bin(x).count("1"), x)) + return arr ``` ### **Java** ```java - +class Solution { + public int[] sortByBits(int[] arr) { + int n = arr.length; + for (int i = 0; i < n; i++) { + arr[i] += Integer.bitCount(arr[i]) * 100000; + } + Arrays.sort(arr); + for (int i = 0; i < n; i++) { + arr[i] %= 100000; + } + return arr; + } +} ``` ### **...** diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.java b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.java new file mode 100644 index 0000000000000..0fd703bf45a77 --- /dev/null +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.java @@ -0,0 +1,13 @@ +class Solution { + public int[] sortByBits(int[] arr) { + int n = arr.length; + for (int i = 0; i < n; i++) { + arr[i] += Integer.bitCount(arr[i]) * 100000; + } + Arrays.sort(arr); + for (int i = 0; i < n; i++) { + arr[i] %= 100000; + } + return arr; + } +} \ No newline at end of file diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.py b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.py new file mode 100644 index 0000000000000..09df16ec4b81a --- /dev/null +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/Solution.py @@ -0,0 +1,4 @@ +class Solution: + def sortByBits(self, arr: List[int]) -> List[int]: + arr.sort(key=lambda x: (bin(x).count("1"), x)) + return arr \ No newline at end of file