# 一起学Rust-实战leetcode（五）

```输入: 123

```输入: -123

```输入: 120

x = 123，

x % 10 = 3，x = floor(x / 10) = 12，

x % 10 = 2，x = floor(x/10) = 1，

x % 10 = 1。x = floor(x/10) = 0，停止。

ret = 0

x % 10 = 3，ret = ret * 10 + 3 = 3

x % 10 = 2，ret = ret * 10 + 2 = 30 + 2

x % 10 = 1，ret = ret * 10 + 1 = 320 + 1

```fn reverse(x: i32) -> i32 {
let mut x = x;
let mut result:Option<i32> = Some(0);

loop {
if x == 0 {
break;
}
let tmp_num = x % 10;
x = x / 10;

result = result.unwrap().checked_mul(10);
if result.is_none() {
return 0_i32;
}

if result.is_none() {
return 0_i32;
}
}

result.unwrap()
}```

checked_mul(y) 乘法，可以由数字或者数字变量直接调用，需要明确数字类型，此函数结果会返回Option<T>类型，溢出范围则返回None。

unwrap() 获取枚举内的值，会获取枚举变量的所有权。

```#[lang = "i32"]
impl i32 {
int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
"0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
"[0x12, 0x34, 0x56, 0x78]", "", "" }
}```

i32 定义的方法内部是通过 int_impl! 宏展开的方法。int_impl! 宏内对checked_mul 定义了文档、文档内测试和方法体。

```doc_comment! {
concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
overflow occurred.

# Examples

Basic usage:

```
", \$Feature, "assert_eq!(", stringify!(\$SelfT),
"::max_value().checked_mul(1), Some(", stringify!(\$SelfT), "::max_value()));
assert_eq!(", stringify!(\$SelfT), "::max_value().checked_mul(2), None);",
\$EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if b {None} else {Some(a)}
}
}```

34 篇文章13 人订阅

0 条评论

## 相关文章

11210

7910

6220

### Python学习笔记（六）——面向对象编程

class后面紧接着是类名，即Student，类名通常是大写开头的单词，紧接着是(object)，表示该类是从哪个类继承下来的，继承的概念我们后面再讲，通常，如...

6210

7020

9610

5910

13310

55520

7310