// 121 true
// -121 false
// 10 false
// 123 false 根据第三种 我额外加的测试用例
//字符串方法
pub fn is_palindrome(x: i32) -> bool {
let x_str = x.to_string();//Chars是一个实现了Iterator trait的结构体,它允许你逐个访问字符串中的字符。
let reversed_str: String = x_str.chars().rev().collect();// 拆了在翻转再合上 用collect变量显式指明了类型
x_str == reversed_str
}
//数学拆分方法
pub fn is_palindrome2(x: i32) -> bool {
// 边界判断,负数不是回文
if x < 0 {
return false;
}
let mut div = 1;
// 找到最高位的权重
while (x as u64) / (div as u64) >= 10 {
div *= 10;
}
let mut num = x; //因为x不可变
while num > 0 { //
let left = num / div;//左位 121为例 1 2
let right = num % 10;//右位 121为例 1 2
if left != right { // 121为例 false
return false;
}
num = num % div / 10;// 121为例 去首位 去末尾 多运算符时候 不要依赖括号
div /= 100;//去首位 去末尾后 消除两位权重 /是向零取整 以121为例 121 1 0
}
true
}
//反转一半数字
pub fn is_palindrome3(x: i32) -> bool {
// 如果x是负数,或者x的个位是0(除非x本身就是0),则x不可能是回文数
if x < 0 || (x % 10 == 0 && x != 0) {
return false;
}
let mut reverted_number = 0;
let mut original_x = x; // 保存原始x的值,以便之后进行比较
// 当原始数大于翻转后的数时,继续翻转
while original_x > reverted_number {// 以121为例 121 0 12 1 1 12 以123为例 123 0 12 3 1 32 原始小于翻转 原始位数x-i 翻转位数i
reverted_number = reverted_number * 10 + original_x % 10;//取得末尾 如果有前面的数会位数增加 121为例 1 12 123为例 3 32
original_x /= 10;//去1位末尾 121为例 12 1 12 1
}
// 如果x是偶数位数,则reverted_number应该和original_x相等
// 如果x是奇数位数,则去除reverted_number的个位后应该与original_x相等
original_x == reverted_number || original_x == (reverted_number / 10)// 奇数位是翻转后多一位
}
fn main() {
assert_eq!(is_palindrome(121), true);
assert_eq!(is_palindrome(-121), false);
assert_eq!(is_palindrome(10), false);
assert_eq!(is_palindrome(123), false);
assert_eq!(is_palindrome2(121), true);
assert_eq!(is_palindrome2(-121), false);
assert_eq!(is_palindrome2(10), false);
assert_eq!(is_palindrome2(123), false);
assert_eq!(is_palindrome3(121), true);
assert_eq!(is_palindrome3(-121), false);
assert_eq!(is_palindrome3(10), false);
assert_eq!(is_palindrome3(123), false);
}
leetcode简单题2 N.9 回文数 rust描述
于 2024-06-27 14:06:22 首次发布