| 29 | } |
| 30 | |
| 31 | fn num2str_stk(mut num: i32, base: i32) -> String { |
| 32 | let digits: [&str; 16] = ["0","1","2","3","4","5","6","7", |
| 33 | "8","9","A","B","C","D","E","F"]; |
| 34 | |
| 35 | let mut rem_stack = Stack::new(); |
| 36 | while num > 0 { |
| 37 | if num < base { |
| 38 | rem_stack.push(num); // 不超过 base 直接入栈 |
| 39 | } else { // 超过 base 余数入栈 |
| 40 | rem_stack.push(num % base); |
| 41 | } |
| 42 | num /= base; |
| 43 | } |
| 44 | |
| 45 | // 出栈余数并组成字符串 |
| 46 | let mut numstr = "".to_string(); |
| 47 | while !rem_stack.is_empty() { |
| 48 | numstr += digits[rem_stack.pop().unwrap() as usize]; |
| 49 | } |
| 50 | |
| 51 | numstr |
| 52 | } |
| 53 | |
| 54 | fn main() { |
| 55 | let num = 100; let sb = num2str_stk(100, 2); |