CODEKATA 21 ~ 25

Tak Jeon·2024년 12월 30일

알고리즘

목록 보기
50/101

21번 하샤드 수

class Solution {
    public boolean solution(int x) {
        int harshad = x;
        int sum = 0;
        while(x > 0){
            sum += x % 10;
            x /= 10;
        }
        return (harshad % sum) == 0;
    }
}

22번 두 정수 사이의 합

class Solution {
    public long solution(int a, int b) {
        long answer = 0;
        if(a > b){
            int temp = a;
            a = b;
            b = temp;
        }
        for(int i = a ; i <= b ;i ++){
            answer += i;
        }
        return answer;
    }
}

23번 콜라츠 추측

class Solution {
    public int solution(int num) {
        long n = (long)num;
        int answer = 0;
        while(answer <= 500){
            if(n == 1) break;
            
            if(n % 2 == 0){
                n /= 2;
            }else{
                n = n * 3 + 1;
            }
            
            answer++;
        }
        return answer > 500 ? -1 : answer;
    }
}

24번 서울에서 김서방 찾기

class Solution {
    public String solution(String[] seoul) {
        String answer = "";
        for(int i = 0 ; i < seoul.length ; i++){
            if(seoul[i].equals("Kim")){
                return "김서방은 " + i + "에 있다";
            }
        }
        return answer;
    }
}

25번 나누어 떨어지는 숫자 배열

import java.util.*;

class Solution {
    public int[] solution(int[] arr, int divisor) {
        ArrayList<Integer> list = new ArrayList<>();
        for(int i = 0 ; i < arr.length ; i++){
            if(arr[i] % divisor == 0){
                list.add(arr[i]);
            }
        }
        Collections.sort(list);
        if(list.size() == 0){
            list.add(-1);
        }
        int[] answer = new int[list.size()];
    
        for(int i = 0 ; i < list.size(); i++){
            answer[i] = list.get(i);
        }
        return answer;
    }
}
profile
문제 해결을 좋아하는 개발자 입니다 :)

0개의 댓글