class Solution {
public:
// 输入 x是任意整数
bool isPalindrome(int x) {
// 提问:不修改原来变量情况下,如果获取整数x=121的最后一个位置(个位),如果获取一个整数的第一个位置(千位置)
// 自然想到的是字符串,还有吗?字符串增加空间
// 遍历方式:最后一个位置不断变少方式 12->1,
// 遍历方式:重新组装 不断变大方式 1,12,121
// 需要新增一个变量
if (x < 0)
return false; // while遍历条件
int number1 = x;
unsigned int number2 = 0; // 翻转后组合新的整数
while (number1 > 0) {
// 获取最后一个位置
int temp = number1 % 10;
number1 = number1 / 10;
number2 = number2 * 10 + temp;
}
return x == number2;
}
};
//impl 为结构体/枚举实现方法
impl Solution {
pub fn is_palindrome(x: i32) -> bool {
if x < 0 {
return false;
}
let pa_number1 = x as u32;// 确保类型一致 翻转前
let mut pa_numer2:u32 = 0; // 翻转后
let mut temp = x as u32;// 确保类型一致 翻转前
//字符串翻转交换位置,整数翻转呢?
while temp > 0 {
pa_numer2 = pa_numer2*10 + temp%10;//Rust 不允许直接进行不同类型的运算
temp = temp/10;
}
return pa_numer2 == pa_number1;
}
}
//1 变量默认是不可改变的(immutable)
//2 as u32 类型转换
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 :
return False # 负数 & 以 0 结尾的数不是回文数(除了 0 本身)
reversed_num = 0
temp_x = x # 复制 x,防止修改原值
while temp_x > 0:
reversed_num = reversed_num * 10 + temp_x % 10
temp_x //= 10 # 整除 10,去掉最后一位
return reversed_num == x # 判断是否回文
//和c++语法不同 返回值在函数后面,
// 遍历类型声明也在函数后面
func isPalindrome(x int) bool {
if x < 0 {
return false
}
number1 := int64(x) // 翻转前变量统一转换为 int64,防止类型不匹配
temp := int64(x) // 统一转换为 int64
var number2 int64 = 0 // 翻转后的变量
// Go 语言只有 for 循环,没有 while
for temp > 0 {
number2 = number2*10 + temp%10
temp /= 10
}
return number1 == number2
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。