题目:

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

题目翻译:

判断一个数,是不是回文

解题思路:

  1. 所有负数,能被10整除的数字都不是回文
  2. 直接将数字倒转,也就是原数字去掉个位,新的数字乘以10,加上原数字去掉的个位
  3. 并不用完全倒转,等原数字小于新数字的时候,就可以判断,如果原数字位数为偶数,比如1221,那么经过变换,原数字变为12,新数字也为12,所以是回文;如果原数字位数是奇数,如121,那么经过变换,原数字为1,新数字为12,原数字等于新数字除以10,也是回文

代码

fn is_palindrome(x: i32) -> bool {
        if x < 0 || (x != 0 && x % 10 == 0) {
            return false;
        }

        let mut tmp: i32 = x;
        let mut recv: i32 = 0;
        while tmp > recv {
            recv = recv * 10 + tmp % 10;
            tmp = tmp / 10;
        }

        return tmp == recv || tmp == recv/10;
}

KuHa
21 声望6 粉丝

会写很多种hello world