https://www.acmicpc.net/problem/1427
1427번: 소트인사이드
첫째 줄에 정렬하려고 하는 수 N이 주어진다. N은 1,000,000,000보다 작거나 같은 자연수이다.
www.acmicpc.net
내가 쓴 답안은 아래와 같다.
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String tempN = Integer.toString(N);
int tempNLength = tempN.length();
Integer[] iArray = new Integer[tempNLength];
for(int i = 0; i < tempNLength ; i++) {
iArray[i] = tempN.charAt(i)-'0';
}
Arrays.sort(iArray, Collections.reverseOrder());
for(int i = 0; i < tempNLength ; i++) {
System.out.print(iArray[i]);
}
}
}
charAt()
String으로 저장된 문자열 중에서 한 글자만을 선택해서 char타입으로 변환해주는 메소드.
사용 방법
참조변수.charAt(index번호);
예시
Char c = ' ';
String str = "안녕하세요";
c=str.charAt(0);
System.out.println(c);
//출력 결과: 안
참고
https://colossus-java-practice.tistory.com/31
[자바 프로그래밍 기초] 4. charAt()에 대해서 알아보자.
이번에 알아볼 charAt()이라는 녀석은 이전에 Scanner에 대해서 알아볼 적에 잠시 등장했던 녀석이다. 오늘은 이 녀석이 도대체 뭐하는 녀석이며 어떻게 사용하는지에 대해서 알아보려고 한다. 1. cha
colossus-java-practice.tistory.com
char to int
방법
char-'0'
답안 코드 일부
iArray[i] = tempN.charAt(i)-'0';
Collections 사용시 주의점
Collections는 기본적으로 Object를 상속한 클래스에 대해서 사용 가능한 인터페이스이므로
String, Integer, Double 등과 같은 Object 타입에 배열은 sort에 Collections.reverseOrder() 사용이 가능하고
기본 타입인 int, double, char, float 등은 사용이 불가능하다.
기본타입의 배열을 Object를 상속하는 Wrapper 클래스로 박싱해주어야 역순정렬도 가능하다.
(더보기 참고: 래퍼 클래스(Wrapper Class) 및 int vs Integer)
래퍼 클래스(Wrapper Class)가 필요한 경우
- 매개변수로 객체를 필요로 할 때
- 기본형 값이 아닌 객체로 저장해야할 때
- 객체 간 비교가 필요할 때
int vs Integer 차이점
int: 자료형(primitive type)
- 산술 연산 가능
- null로 초기화 불가
Integer: 래퍼 클래스(wrapper class)
- unboxing하지 않을 경우 산술 연산 불가능함.
- null값 처리 가능
boxing : primitive type -> wrapper class 변환 ( int to Integer )
unboxing : wrapper class -> primitive type 변환 ( Integer to int )
출처
int와 Integer는 무엇이 다른가
int와 Integer는 무엇이 다른가 // 기본부터 다시 시작하기
velog.io
그래서 여기서 int[]가 아닌 Integer[]를 썼다.
Integer[] iArray = new Integer[tempNLength];
//...생략
Arrays.sort(iArray, Collections.reverseOrder());
참고 및 출처
https://bangu4.tistory.com/287
[Java] int, String 배열 오름차순/내림차순 정렬
배열은 기본적으로 Arrays.Sort()를 이용해서 정렬한다. 1차원 배열은 Sort에 해당 배열을 인자로 넣어 기본적으로 오름차순 정렬을 하는데, 내림차순 정렬을 하기 위해서는 두번째 인자로 Collections.r
bangu4.tistory.com
'Programming Language > JAVA' 카테고리의 다른 글
[JAVA] 백준 11047 동전 0 JAVA 문제풀이(feat.더러운 코드) (0) | 2022.09.02 |
---|---|
[JAVA] BufferedReader, BufferedWriter (0) | 2022.08.23 |
[JAVA]텍스트 추출 방법과 Int로 변형하는 방법. (0) | 2022.02.03 |