08.01 pre-edu

Inabang·2021년 8월 1일
0

알고리즘

목록 보기
3/9

기초 알고리즘 Part2

1. 문자열 다루기 기본

문자열 s의 길이가 4 혹은 6이고 숫자로만 구성돼있는지 확인해주는 함수를 완성하라.
예를 들어 s가 "a234"이면 false "1234"라면 True를 리턴하면된다.

class Solution {
    public boolean solution(String s) {
        boolean answer = false;
        char[] tempc = s.toCharArray();
        if (tempc.length == 4 || tempc.length == 6){
            answer = true;
        }
        for (int i = 0; i < tempc.length; i++){
            if(!Character.isDigit(tempc[i])){
                answer = false;
            }
        }
        return answer;
    }
}

2. 정수 내림차순으로 배치하기

정수 n을 매개변수로 입력받고 n의 각 자릿수를 큰것부터 작은순으로 정렬한 새로운 정수를 리턴하라.
자바 기본 정렬함수 안쓰고 직접 정렬함수 만들다가 시간 다 날려먹었다..

import java.util.*;
class Solution {
    public long solution(long n) {
        long answer = 0;
        String anstmp = "";
        String[] nstr = Long.toString(n).split("");              
        Arrays.sort(nstr);       
        for(int i = nstr.length - 1; i >= 0; i--){
            anstmp += nstr[i];
        }        
        answer = Long.parseLong(anstmp);
        return answer;
    }
}

3. 자연수 뒤집어 배열로 만들기

자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴하라.
예를들어 n이 12345면 [5,4,3,2,1]로 리턴한다.

class Solution {
    public int[] solution(long n) {
        int[] answer = {};
        String temp = "";
        String[] arr = Long.toString(n).split("");   
        answer = new int[arr.length];     
        for (int i = arr.length - 1; i >= 0; i--){
            int k = (arr.length - 1) - i;
            answer[k] = Integer.parseInt(arr[i]);
        }
        return answer;
    }
}

4. 핸드폰 번호 가리기

전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 "*"으로 가린 문자열을 맅턴하는 함수를 완성하라.

class Solution {
    public String solution(String phone_number) {
        String answer = "";
        char[] tempc = phone_number.toCharArray(); 
        for (int i = 0; i < tempc.length; i++){
            if(i >= (tempc.length -4)){
                answer += Character.toString(tempc[i]);
            }else{
                answer += "*";
            }
        }
        return answer;
    }
}

5.K번째수

배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
2에서 나온 배열의 3번째 숫자는 5입니다.
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.

import java.util.Arrays;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = {};
        answer = new int[commands.length];
        int[] temp = {};
        int sn = 0;
        int en = 0;
        int index = 0;
        int key = 0;
        for (int i = 0; i < commands.length; i++){
            for (int j = 0; j < commands[i].length; j++){
                sn = commands[i][0];
                en = commands[i][1];
                index = commands[i][2];
                temp = new int[(en - sn + 1)];
                int x = 0;  
                if(sn == en){
                    key = array[en - 1];
                    continue;
                } else{
                    for (int k = sn - 1; k < en; k++){
                        temp[x++] = array[k];
                    }
                    Arrays.sort(temp);
                    key = temp[index - 1];
                }
            }
            answer[i] = key;
        }
        return answer;
    }
}

정말 더럽게 짠거같다 일단 돌아는가는데 효율면에선 매우 구려보임.. 이걸 메소드로 빼서 리팩토링 한다면 더 코드가 볼만할거같다.
밑의 코드는 모범 답안이다.

import java.util.Arrays;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        for(int i=0; i<commands.length; i++){
            int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            Arrays.sort(temp);
            answer[i] = temp[commands[i][2]-1];
        }
        return answer;
    }
}

6. 하샤드 수

양의 정수 x가 하샤드 수이려면 x의 자릿수의 합으로 x가 나누어져야 합니다. 예를 들어 18의 자릿수 합은 1+8=9이고, 18은 9로 나누어 떨어지므로 18은 하샤드 수입니다. 자연수 x를 입력받아 x가 하샤드 수인지 아닌지 검사하는 함수, solution을 완성해주세요.

class Solution {
    public boolean solution(int x) {
        boolean answer = true;
        String temp = Integer.toString(x);
        char[] temp2 = temp.toCharArray();
        int key = 0;
        for (int i = 0; i < temp2.length; i++){
            key += (int)(temp2[i] - 48);
        }
        if(x % key == 0){
            answer = true;
        }else{
            answer = false;
        }
        return answer;
    }
}

7. 나누어 떨어지는 숫자 배열

array의 각 element 중 divisor로 나누어 떨어지는 값을 오름차순으로 정렬한 배열을 반환하는 함수, solution을 작성해주세요.
divisor로 나누어 떨어지는 element가 하나도 없다면 배열에 -1을 담아 반환하세요.

import java.util.Arrays;
class Solution {
    public int[] solution(int[] arr, int divisor) {
        int[] answer = {};
        String temp = Arrays.toString(arr);
        int x = 0;
        int count = 0;
        for (int i = 0; i < arr.length; i++){
            if (arr[i] % divisor == 0){
                x++;
            } 
        }
        if (x == 0){
            answer = new int[1];
            answer[0] = -1;
        } else {
            answer = new int[x];
        }
        for (int j = 0; j < arr.length; j++){
            if (arr[j] % divisor == 0){
                answer[count++] = arr[j];
            } 
        }
        Arrays.sort(answer);
        return answer;
    }
}

0개의 댓글