Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- Counting
- Class
- Tree
- Binary Search
- 구현
- java
- Math
- greedy
- Binary Tree
- hash table
- SQL
- string
- two pointers
- dynamic programming
- Stack
- bit manipulation
- Method
- implement
- database
- 자바
- 코딩테스트
- 코테
- geometry
- Data Structure
- Matrix
- array
- sorting
- simulation
- 파이썬
- Number Theory
Archives
- Today
- Total
코린이의 소소한 공부노트
[LeetCode/Easy] 2231. Largest Number After Digit Swaps by Parity 본문
코딩테스트 풀이/JAVA
[LeetCode/Easy] 2231. Largest Number After Digit Swaps by Parity
무지맘 2023. 6. 21. 13:111. Input
1) int num
2. Output
1) num의 각 자리 숫자들끼리 다음 조건에 따라 순서를 바꿨을 때 만들 수 있는 가장 큰 숫자를 반환
- 짝수는 짝수끼리, 홀수는 홀수끼리 자리를 바꿀 수 있다.
- num의 각 자리 숫자가 ‘홀짝짝홀’이었다면, 순서를 바꾸고 만든 숫자도 ‘홀짝짝홀’이어야 한다.
3. Constraint
1) 1 <= num <= 10^9
4. Example
Input: num = 65875 -> Output: 87655
설명:
- 짝수는 6, 8이 있고, 홀수는 5, 7, 5가 있다.
- 만들 수 있는 수는 67855, 85657 등이 있지만, 가장 큰 수는 87655이므로 이것을 반환한다.
5. Code
1) 첫 코드(2023/06/21)
class Solution {
public int largestInteger(int num) {
List<Integer> odd = new ArrayList<>();
List<Integer> even = new ArrayList<>();
int origin = num;
while(num>0){
int n = num%10;
num /= 10;
if(n%2==0) even.add(n);
else odd.add(n);
}
odd.sort(Comparator.naturalOrder());
even.sort(Comparator.naturalOrder());
int a = 0, b = 0;
StringBuilder sb = new StringBuilder();
while(origin>0){
int n = origin%10;
origin /= 10;
if(n%2==0) sb.append(even.get(a++));
else sb.append(odd.get(b++));
}
return Integer.valueOf(sb.reverse().toString());
}
}
- 26%, 95%
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[백준 온라인 저지] 17103. 골드바흐 파티션 (0) | 2023.06.22 |
---|---|
[백준 온라인 저지] 1018. 체스판 다시 칠하기 (0) | 2023.06.22 |
[LeetCode/Easy] 2164. Sort Even and Odd Indices Independently (0) | 2023.06.21 |
[LeetCode/Easy] 2144. Minimum Cost of Buying Candies With Discount (0) | 2023.06.21 |
[LeetCode/Easy] 2085. Count Common Words With One Occurrence (0) | 2023.06.21 |