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

Function num2str_stk

code/chapter04/num2str_stk.rs:31–52  ·  view source on GitHub ↗
(mut num: i32, base: i32)

Source from the content-addressed store, hash-verified

29}
30
31fn 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
54fn main() {
55 let num = 100; let sb = num2str_stk(100, 2);

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