From ad8ba9184d4c3b6eff9d251a8677853075975fce Mon Sep 17 00:00:00 2001 From: Andrew Guschin Date: Thu, 16 Feb 2023 21:43:45 +0400 Subject: =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B0?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80=D0=B6=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=BD=D0=B5=D0=B4=D0=B5=D1=81=D1=8F=D1=82=D0=B8=D1=87=D0=BD?= =?UTF-8?q?=D1=8B=D1=85=20=D1=81=D0=B8=D1=81=D1=82=D0=B5=D0=BC=20=D1=81?= =?UTF-8?q?=D1=87=D0=B8=D1=81=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B8=20?= =?UTF-8?q?=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA=D0=B0=20=D0=BE?= =?UTF-8?q?=D1=88=D0=B8=D0=B1=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sem2/src/mpn.rs | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-) (limited to 'sem2/src/mpn.rs') diff --git a/sem2/src/mpn.rs b/sem2/src/mpn.rs index 27f94e0..ecc1d5c 100644 --- a/sem2/src/mpn.rs +++ b/sem2/src/mpn.rs @@ -8,16 +8,21 @@ pub struct Number { } impl Number { - pub fn parse(snum: &str) -> Result { - let radix = 10_usize; + pub fn parse(snum: &str, radix: usize) -> Result { let snum = snum.as_bytes(); let mut digits = Vec::new(); for i in (0..snum.len()).rev() { - let digit = snum[i] - '0' as u8; - if digit as usize >= radix { - return Err("Аргумент не является числом"); - } else { - digits.push(digit); + match Number::parse_digit(snum[i]) { + Some(digit) => { + if digit as usize >= radix { + return Err("Аргумент не является числом"); + } else { + digits.push(digit); + } + } + None => { + return Err("Аргумент не является числом"); + } } } return Ok(Number { radix, digits }); @@ -26,12 +31,31 @@ impl Number { pub fn len(&self) -> usize { self.digits.len() } + + fn parse_digit(c: u8) -> Option { + if c >= 'a' as u8 { + Some(c - 'a' as u8 + 10_u8) + } else if c >= '0' as u8 { + Some(c - '0' as u8) + } else { + None + } + } } impl fmt::Display for Number { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for i in (0..self.digits.len()).rev() { - write!(f, "{}", self.digits[i])?; + let digit = if self.digits[i] > 9 { + ('a' as u8 - 10 + self.digits[i]) as char + } else { + ('0' as u8 + self.digits[i]) as char + }; + write!(f, "{}", digit)?; + } + + if self.radix != 10 { + write!(f, "_{}", self.radix)?; } return Ok(()); } -- cgit v1.2.3