MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / num2str_stk

Function num2str_stk

publication/code/chapter05/num2str_stk.rs:33–57  ·  view source on GitHub ↗
(mut num: i32, base: i32)

Source from the content-addressed store, hash-verified

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

Callers 1

mainFunction · 0.70

Calls 4

pushMethod · 0.45
to_stringMethod · 0.45
is_emptyMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected