Palindrome Number 判断是否为回文数
问题描述
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.
解答思路
要判断整数x是否是回文数字,分为两种情况:
一:如果x为负数,则直接返回false;
二:如果x为非负数,则一直对x进行取余操作,获取到当前x的最低位数值,并将其作为新数值y的最高位。直至x取到最高位为止。最后对比x和y是否相等,相等则判定为true,反之,false。
代码如下:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
int compare = 0;
int ope = x;
int tail = 0;
while (ope != 0){
tail = ope % 10;
compare *= 10;
compare += tail;
ope /= 10;
}
if (compare == x){
return true;
}else return false;
}
}
leetcode上最终效果如下:
版权说明:题目来自LeetCode,解决方案原创