实现思路
- 定义一个函数,接收一个整数和表示进制的参数。
- 根据不同的进制进行相应的转换逻辑。可以通过不断对数字取模和整除操作,获取每一位的数值。
- 将获取到的每一位数值转换为对应的字符(对于16进制,需要处理
A - F
)。
- 由于获取每一位数值的顺序是从低位到高位,需要将结果字符串反转。
- 输出最终转换后的字符串。
核心代码
fn custom_format(num: i32, base: i32) {
let mut result = String::new();
let mut n = num;
let mut is_negative = false;
if n < 0 {
is_negative = true;
n = -n;
}
loop {
let digit = (n % base) as u8;
let digit_char = if digit < 10 {
(b'0' + digit) as char
} else {
(b'A' + digit - 10) as char
};
result.insert(0, digit_char);
n /= base;
if n == 0 {
break;
}
}
if is_negative {
result.insert(0, '-');
}
println!("{}", result);
}
使用示例
fn main() {
custom_format(42, 2);
custom_format(42, 8);
custom_format(42, 10);
custom_format(42, 16);
}