본문 바로가기

Algorithm

자바 알고리즘 연습(5)

하샤드 수

class Solution {
    public boolean solution(int x) {
        boolean answer = false;
        int firstNumber = x;
        int numberSum = 0;
        while (x > 0) {
            numberSum += x % 10;
            x = x / 10;  
        }
        
        if(firstNumber % numberSum == 0){
            answer = true;
        }
        return answer;
    }
}

 

두 정수 사이의 합

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;
    }
}

 

콜라츠 추측

class Solution {
    public int solution(long num) {
        int answer = 1;
        
        if (num == 1) return 0;
        
        for(; answer < 502; answer++){
            
            if(num % 2 == 0){
                num = num / 2;
            } else {
                num = num * 3 + 1;
            }
            
            if (num == 1){
                break;
            }
            
        }
        
        if (answer == 502){
            return -1;
        } else {
            return answer;
        }
    }
}

 

서울에서 김서방 찾기

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

 

나누어 떨어지는 숫자 배열

import java.util.*;

class Solution {
    public int[] solution(int[] arr, int divisor) {
        ArrayList<Integer> arrList = new ArrayList<Integer>();
        
        for (int a : arr){
            if (a % divisor == 0){
                arrList.add(a);
            }
        }
        
        Collections.sort(arrList);
        
        if(arrList.size() == 0){
            int[] answer = {-1};
            return answer;
        }
        
        int[] answer = new int[arrList.size()];
        
        for (int i = 0; i < arrList.size(); i++){
            answer[i] = arrList.get(i);
        }
        return answer;
    }
}