알고리즘/알고리즘 문제
[java] 진법 변환 알고리즘(기수 변환)
희랍인 조르바
2018. 8. 7. 11:18
해당 알고리즘은 2진수~36진수까지 진법 변환이 가능한 알고리즘이다.
아래 사진에서 보는 것과 같이 구현해낸 알고리즘이다.
나머지를 통해 거꾸로 읽어서 원하는 진수로 변환된 수를 알아낼 수 있다.
* 소스
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class CardinalConversion { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int quotient = Integer.parseInt(br.readLine()); // 주어지는 수이자 나중에는 몫 int cardinalNum = Integer.parseInt(br.readLine()); // 변환하고자 하는 진법 String character = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; List<Character> output = new ArrayList<>(); bw.write("주어진 수이자 몫이되는 수 : "+ quotient); bw.newLine(); bw.write("변환하고자 하는 진수 : " + cardinalNum); bw.newLine(); while(quotient != 0) { output.add(character.charAt(quotient%cardinalNum)); // 나머지가 저장됨 quotient /= cardinalNum; } Collections.reverse(output); bw.write("["); for(Character convertedNum : output) { bw.write(convertedNum); } bw.write("]"); bw.flush(); } } | cs |
결과:
각 자리의 문자를 미리 만들어놓고 나머지를 통해 문자 순서를 찾아 배열에 저장한다.
저장된 나머지를 거꾸로 읽어주어야 하므로 Collections.reverse()를 통해 순서를 뒤집어 주고 그대로 출력하면
원하는 진수로 변환된 수를 확인할 수 있다.