백준/Java

[백준 자바] 1550번(16진수) - 16진수를 10진수로 바꾸기

gamzaggang7 2024. 6. 19. 21:54
728x90

난이도 - 브론즈 2

문제

16진수 수를 입력받아서 10진수로 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 16진수 수가 주어진다. 이 수의 최대 길이는 6글자이다. 16진수 수는 0~9와 A~F로 이루어져 있고, A~F는 10~15를 뜻한다. 또, 이 수는 음이 아닌 정수이다.

출력

첫째 줄에 입력으로 주어진 16진수 수를 10진수로 변환해 출력한다.

 


 

728x90

0~F를 문자열로 저장하여 16진수의 각 자리에 해당하는 문자와 일치하는 문자열의 인덱스에 16의 거듭제곱 값을 곱한다.

import java.io.*;

public class Main1550 {
  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

    String hexadecimal = br.readLine();

    bw.write(String.valueOf(hexadecimalToDecimal(hexadecimal)));

    bw.flush();
    br.close();
    bw.close();
  }

  static int hexadecimalToDecimal(String hexadecimal) {
    String dchar = "0123456789ABCDEF";

    int result = 0;

    for (int i = 0; i < hexadecimal.length(); i++) {
      result += dchar.indexOf(hexadecimal.charAt(hexadecimal.length() - 1 - i))
          * Math.pow(16, i);
    }

    return result;
  }
}

728x90