본문 바로가기

프로그래머스

프로그래머스 - 문자열 내 마음대로 정렬하기 내 코드 - 선택정렬 사용class Solution { public String[] solution(String[] strings, int n) { String[] answer = {}; String tmpStr; /** * 선택정렬 사용 */ for (int i = 0; i strings[j].charAt(n)) { tmpStr = strings[j]; strings[j] = strings[i]; strings[i] = tmpStr; /** * 비교 문자가 같은 경우 */ } ..
프로그래머스 - 같은 숫자는 싫어 내 코드 - Deque 사용import java.util.*; public class Solution { public int[] solution(int []arr) { int[] answer = {}; /** * Deque 자료구조 사용 */ Deque deque = new ArrayDeque(); for (int i = 0; i < arr.length; i++) { if (i == 0) { deque.push(arr[i]); } else { if (deque.getLast() != arr[i]) { /** * 주의 * * deque.push()는 앞부분에 자료 삽입 * deque.add()는 뒷부분에 자료 삽입 */ deque.add(arr[i]); } } } answer = new int[deque...
프로그래머스 - 콜라츠 추측 내 코드 - 재귀함수 사용class Solution { int cnt = 0; public int solution(int num) { int answer = circle(num); return answer; } /** * 재귀함수 사용 * * 계산과정에서 cricle의 매개변수가 * int 범위를 벗어날 수가 있다. */ public int circle(long num) { if (num == 1) { return cnt >= 500 ? -1 : cnt; } else { if (num % 2 == 0) { circle(Long.valueOf(num) / 2); } else { circle(Long.valueOf(num) * 3 + 1); } cnt++; } return cnt >= 500 ? -1 : c..
프로그래머스 - 자연수 뒤집어 배열로 만들기 내 코드 import java.util.Arrays; class Solution { public int[] solution(long n) { int[] answer = {}; String[] strs = String.valueOf(n).split(""); String tmpStr; for (int i = 0; i Integer.parseInt(i)).toArray()..
프로그래머스 - 정수 내림차순으로 배치하기 import java.util.Arrays; import java.util.Collections; class Solution { public long solution(long n) { long answer = 0; String nStr = String.valueOf(n); /** * Collections.reverseOrder()를 사용하기 위해 Integer로 선언 */ Integer[] arrs = new Integer[nStr.length()]; for (int i = 0; i < nStr.length(); i++) { arrs[i] = nStr.charAt(i) - 48; } /** * 내림차순 정렬 */ Arrays.sort(arrs, Collections.reverseOrder()); for ..
프로그래머스 - 하샤드 수 class Solution { public boolean solution(int x) { boolean answer = true; int eachTotal = eachTotal(x); answer = x % eachTotal == 0 ? true : false; return answer; } /** * 각 자리수 합 구하기 * @param x * @return */ public int eachTotal(int x) { int sum = 0; int nmg; while(x > 0) { nmg = x % 10; sum += nmg; x /= 10; } return sum; } } 다른 사람 코드 - String.valueOf(x);를 사용해 각 자리에 대한 접근을 좀 더 쉽게 했다.class Solution..
프로그래머스 - 행렬의 덧셈 class Solution { public int[][] solution(int[][] arr1, int[][] arr2) { int[][] answer = {}; answer = new int[arr1.length][arr1[0].length]; for (int i = 0; i < answer.length; i++) { for (int j = 0; j < answer[i].length; j++) { answer[i][j] = arr1[i][j] + arr2[i][j]; } } return answer; } }
프로그래머스 - 직사각형 별찍기 import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); for (int i = 0; i < b; i++) { for (int j = 0; j < a; j++) { System.out.print("*"); } System.out.println(); } } }