본문 바로가기
알고리즘/백준

백준 11005 진법 변환 2 (JAVA 자바 풀이)

by Renechoi 2023. 6. 9.

백준 11005 진법 변환 2 (JAVA 자바 풀이)


 

 


 

 

 

💡 코드 구현

 


public class Main {

	private static final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

	public static void main(String[] args) throws IOException {
		StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
		int n = Integer.parseInt(stringTokenizer.nextToken());
		int m = Integer.parseInt(stringTokenizer.nextToken());

		int initialN = n;
		int initialM = m;
		StringBuilder stringBuilder = new StringBuilder();
		while (true) {
			int remainder = getRemainder(n, m);
			int quotient = getQuotient(n, m);
			n = quotient;

			write(stringBuilder, remainder);

			if (n == initialM) {
				write(stringBuilder, getRemainder(n, m));
				write(stringBuilder, getQuotient(n, m));

				break;
			}
			if (n < initialM) {
				if (quotient == 0) {
					break;
				}
				write(stringBuilder, quotient);
				break;
			}
		}
		System.out.println(stringBuilder.reverse());
	}

	private static void write(StringBuilder stringBuilder, int number) {
		if (number >= 10) {
			char alphabet = (char)(number + 'A' - 10);
			stringBuilder.append(alphabet);
			return;
		}
		stringBuilder.append(number);
	}

	private static int getRemainder(int divisor, int dividend) {
		return divisor % dividend;
	}

	private static int getQuotient(int divisor, int dividend) {
		return divisor / dividend;
	}
}

 

 

말 그대로 brute force 방식의 코드이다.

손으로 푸는 것을 그대로 프로그래밍 하였다. 

 

 

보다 단순하게 다음과 같이 작성할 수도 있다. 

 

 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

   private static final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

   public static void main(String[] args) throws IOException {
      StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
      int number = Integer.parseInt(stringTokenizer.nextToken());
      int base = Integer.parseInt(stringTokenizer.nextToken());
      StringBuilder answer = new StringBuilder();
      while (number > 0) {
         int remainder = number % base;
         if (remainder < 10){
            answer.append(remainder);
         }
         else {
            answer.append((char)('A' + remainder - 10));
         }
         number /= base;
      }

      System.out.println(answer.reverse());
   }
}

 

반응형