Algorithm

자바 알고리즘 연습(3)

김예나 2025. 1. 3. 10:52

자릿수 더하기

public class Solution {
    public int solution(int n) {
        int answer = 0;
        int temp = 0;
        while (n > 0) {
            answer += n % 10;
            n /= 10; 
        }

        return answer;
    }
}

 

약수의 합

class Solution {
    public int solution(int n) {
        int answer = 0;
        for(int i = 1; i <= n; i++){
            if(n % i == 0){
                answer += i;
            }
        }
        return answer;
    }
}

 

나머지가 1이 되는 수 찾기

class Solution {
    public int solution(int n) {
        int answer = 0;
        for (int i = 1; i < 1000000; i++){
            if (n % i == 1){
                answer = i;
                break;
            }
        }
        return answer;
    }
}

 

x만큼 간격이 있는 n개의 숫자

  • 베열 초기화 : float[] a = {1, 2,3 ,4};
  • 크기를 지정하고 나중에 값을 넣을 때 : float[] a = new float[3];
class Solution {
    public long[] solution(int x, int n) {
        long[] answer = new long[n];
        answer[0] = x;
        for (int i = 1; i < n; i++){
            answer[i] = answer[i-1] + x;
        }
        return answer;
    }
}

 

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

  • 배열의 길이 (자릿수)를 알기 위해 temp를 사용
  • answer[idx++] = n % 10; 부분에서 n % 10의 값이 long이기 때문에 answer배열의 타입도 long으로 변경
class Solution {
    public long[] solution(long n) {
        int arrCount = 0;
        long temp = n;
        while (temp > 0){
            temp /= 10;
            arrCount += 1;
        }
        
        long[] answer = new long[arrCount];
        int idx = 0;
        while (n > 0){
            answer[idx++] = n % 10;
            n /= 10;
        }
        return answer;
    }
}