문제 풀이/기타

[백준] 2231 (분해합)

interfacer_han 2023. 11. 9. 16:19

#1 알고리즘

 

#2 코드

#2-1 자바

import java.util.Scanner;

public class Main {
	private static int lowestGenerator = 0;
	
    public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
    	int N = sc.nextInt();
    	sc.nextLine();
    	sc.close();
    	
    	int bunHaeHap;
    	for(int i = 1; i < N; i++) {
    		bunHaeHap = i + digitSum(i);
    		
    		if(bunHaeHap == N) {
    			saveIfLowestGenerator(i);
    		} 
    	}
    	
    	System.out.println(Integer.toString(lowestGenerator));
    }
    
    private static int digitSum(int number) {
    	int sum = 0;
    	
    	String numberString = Integer.toString(number);
    	for(int i = 0; i < numberString.length(); i++) {
    		sum += Character.getNumericValue(numberString.charAt(i));
    	}
    	
    	return sum;
    }
    
    private static void saveIfLowestGenerator(int number) {
    	if(lowestGenerator == 0) {
    		lowestGenerator = number;
    		return;
    	}
    	
    	if(number < lowestGenerator) {
    		lowestGenerator = number;
    	}
    }
}

 

#2-2 코틀린

var lowestGenerator : Int = 0

fun main() {
    val N = readLine()!!.trim().toInt()

    var bunHaeHap = -1
    for(i : Int in 1..(N - 1)) {
        bunHaeHap = i + digitSum(i)

        if(bunHaeHap == N) {
            saveIfLowestGenerator(i)
        }
    }

    println(lowestGenerator.toString())
}

fun digitSum(number : Int) : Int {
    var sum = 0

    for(c : Char in number.toString()) {
        sum += Character.getNumericValue(c)
    }

    return sum
}

fun saveIfLowestGenerator(number: Int) {
    if(lowestGenerator == 0) {
        lowestGenerator = number
        return
    }
    
    if(number < lowestGenerator) {
        lowestGenerator = number
    }
}

'문제 풀이 > 기타' 카테고리의 다른 글

[백준] 10809 (알파벳 찾기)  (0) 2023.11.16
[백준] 2292 (벌집)  (0) 2023.11.10
[백준] 1978 (소수 찾기)  (0) 2023.11.08
[백준] 1436 (영화감독 숌)  (0) 2023.11.03
[백준] 1157 (단어 공부)  (0) 2023.10.31