Problem statement: Write a program that takes two command-line arguments number
and k
. The program should convert number
to base k
. Assume the base is between 2 and 16 inclusive. For bases greater than 10, use the letters A through F to represent the digits 10 through 15, respectively.
This is one of my self-imposed challenges in Rust to become better at it. The problem was taken from Sedgewick Exercise 1.3.21.
Here is my code:
use std::env;
fn main() {
let arguments: Vec<String> = env::args().collect();
let mut number: u32 = arguments[1].parse().unwrap();
let k: u32 = arguments[2].parse().unwrap();
let number_original: u32 = number;
let mut largest_power: u32 = 1;
let mut kary: String = String::new();
while largest_power <= number/k {
largest_power *= k;
}
while largest_power > 0 {
if largest_power > number {
kary.push_str(&format!("{}", "0"));
} else {
let dividend: u32 = number/largest_power;
if number/largest_power < 10 {
kary.push_str(&format!("{}", dividend.to_string()));
number -= dividend*largest_power;
}
else if number/largest_power == 10 {kary.push_str(&format!("{}", "A")); number -= dividend*largest_power;}
else if number/largest_power == 11 {kary.push_str(&format!("{}", "B")); number -= dividend*largest_power;}
else if number/largest_power == 12 {kary.push_str(&format!("{}", "C")); number -= dividend*largest_power;}
else if number/largest_power == 13 {kary.push_str(&format!("{}", "D")); number -= dividend*largest_power;}
else if number/largest_power == 14 {kary.push_str(&format!("{}", "E")); number -= dividend*largest_power;}
else if number/largest_power == 15 {kary.push_str(&format!("{}", "F")); number -= dividend*largest_power;}
}
largest_power /= k;
}
match k {
2..=16 => println!("The number {} at base {} is represented with {}.", number_original, k, kary),
_ => panic!("Base must be between 2 and 16."),
}
}
Is there any way that I can improve my code?