본문 바로가기

컴퓨터 과학/자료구조, 알고리즘

[Rust로 백준 하루 하나] 8-2. 진법 변환 2

문제 (11005번)

10진법 수 N이 주어진다. 이 수를 B진법으로 바꿔 출력하는 프로그램을 작성하시오.

 

10진법을 넘어가는 진법은 숫자로 표시할 수 없는 자리가 있다. 이런 경우에는 다음과 같이 알파벳 대문자를 사용한다.

 

A: 10, B: 11, ..., F: 15, ..., Y: 34, Z: 35

 

입력

첫째 줄에 N과 B가 주어진다. (2 ≤ B ≤ 36) N은 10억보다 작거나 같은 자연수이다.

 

출력

첫째 줄에 10진법 수 N을 B진법으로 출력한다.


풀이

코드

use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let input: Vec<&str> = input.split_whitespace().collect();

    let mut n: usize = input[0].trim().parse().unwrap();
    let b: usize = input[1].trim().parse().unwrap();

    let mut output = String::new();
    let digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if n == 0 {
        output.push('0');
    } else {
        while n > 0 {
            output.push(digits.chars().nth(n % b).unwrap());
            n /= b;
        }
    }

    let result: String = output.chars().rev().collect();
    println!("{}", result);
}

해설

println!("{:?}", result);로 출력하게 되면 출력형식이 맞지 않아 틀리게 된다. 주의할 것


추가 학습

  • 특이사항 없음