728x90
반응형
문제 : 3, 6, 9 가 포함된 숫자에 박수("-") 치기
풀이1 :
String.contains(), String.charAt()을 사용해서 풀이
풀이2 :
정규식(replaceAll) 활용
풀이3 :
replace 사용
풀이1
public class Solution1926 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i = 1; i <= n; i++) {
String str = String.valueOf(i); // ex) i = 23일 때, String으로 바꾸면 str.length = 2
// valueOf를 사용하면 null 값이어도 출력. (Null Pointer Exception 안터짐)
if (str.contains("3") || str.contains("6") || str.contains("9")) {
for (int j = 0; j < str.length(); j++) {
if (str.charAt(j) == '3' || str.charAt(j) == '6' || str.charAt(j) == '9') {
System.out.print("-");
}
}
System.out.print(" ");
} else {
System.out.print(i + " ");
}
}
}
}
풀이2
/**
* 정규식을 활용한 풀이 -> replaceAll
* for (int i = 1; i <= n; i++) {
* String tmp = String.valueOf(i);
*
* if (tmp.contains("3") || tmp.contains("6") || tmp.contains("9")) {
* for (int j = 0; j < tmp.length(); j++) {
* tmp = tmp.replaceAll("[369]", "-");
* }
* tmp = tmp.replaceAll("[0124578]", "");
* }
* System.out.print(tmp + " ");
*
*
* }
*/
풀이3
/**
* replace를 활용한 풀이
* for (int i = 1; i <= n; i++) {
* String tmp = String.valueOf(i);
*
* if (tmp.contains("3") || tmp.contains("6") || tmp.contains("9")) {
* tmp = tmp.replace("3", "-");
* tmp = tmp.replace("6", "-");
* tmp = tmp.replace("9", "-");
*
* tmp = tmp.replace("0", "");
* tmp = tmp.replace("1", "");
* tmp = tmp.replace("2", "");
* tmp = tmp.replace("4", "");
* tmp = tmp.replace("5", "");
* tmp = tmp.replace("7", "");
* tmp = tmp.replace("8", "");
*
* }
* System.out.print(tmp + " ");
* }
*
*/
728x90
반응형
'SWEA' 카테고리의 다른 글
swea 1940 [D2] 가랏! RC카! JAVA (0) | 2023.11.20 |
---|---|
swea 1928 [D2] Base64 Decoder JAVA (0) | 2023.11.20 |
swea 1859 [D2] 백만 장자 프로젝트 JAVA (0) | 2023.11.20 |
swea 1288 [D2] 새로운 불면증 치료법 JAVA (0) | 2023.11.20 |
swea 1285 [D2] 아름이의 돌 던지기 JAVA (0) | 2023.11.20 |