본문 바로가기

분류 전체보기

프로그래머스 - 콜라츠 추측 내 코드 - 재귀함수 사용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(); } } }
프로그래머스 - x만큼 간격이 있는 n개의 숫자 내 코드 - 오답class Solution { public long[] solution(int x, int n) { long[] answer = {}; answer = new long[n]; for (int i = 0; i < n; i++) { /** * 여기서 answer[i]에는 int가 들어감 * * 따라서 만약, * x * (i + 1)이 int 범위를 초과한다면 엉뚱한 값이 들어감 */ answer[i] = x * (i + 1); } return answer; } } 문제에서 -10,000,000
프로그래머스 - 나누어 떨어지는 숫자 배열 내 코드import java.util.ArrayList; import java.util.Collections; import java.util.List; class Solution { public int[] solution(int[] arr, int divisor) { int[] answer = {}; List list = new ArrayList(); for (int num : arr) { if (num % divisor == 0) { list.add(num); } } if (list.size() == 0) { list.add(-1); } else { Collections.sort(list); } answer = new int[list.size()]; for (int i = 0; i < answer.le..