「这是我参与11月更文挑战的第8天,活动详情查看:2021最后一次更文挑战」。
回文数应该是我们小学数学课本就接触过的一类有趣的数字,今天我们用计算机中不同的数据结构对其进行剖析解答。
题目描述
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
题目示例
题目解法
解法一:折中反转数比较法(推荐)
/*
* 整数取折中数
*/
class Solution {
public boolean isPalindrome(int x) {
// 负数或10的倍数false
if (x < 0 || (x % 10 == 0 && x != 0)){
return false;
}
// 个数true
if( x / 10 < 1){
return true;
}
// 折中取反转数
int revertMinddle = 0;
while (revertMinddle < x ) {
revertMinddle = revertMinddle * 10 + x % 10;
x /= 10;
}
return x == revertMinddle || x == revertMinddle / 10;
}
}
解法二:字符串解法之String定位法
/*
* 字符串解法String.charAt
*/
class Solution {
public boolean isPalindrome(int x) {
// 负数或10的整倍数false
if(x < 0 || ( x > 0 && x % 10 == 0)){
return false;
}
// 个数true
if(x / 10 < 1){
return true;
}
String curNumber = x + "";
int length = curNumber.length();
int curIndex = 0;
while(curIndex < length){
if(curNumber.charAt(curIndex) != curNumber.charAt(length - curIndex -1)){
return false;
}
curIndex ++;
}
return true;
}
}
解法三:字符串解法之StringBuilder反转法
/*
* 字符串解法-StringBuilder.reverse
*/
class Solution {
public boolean isPalindrome(int x) {
// 负数或10的倍数false
if (x < 0 || (x % 10 == 0 && x != 0)){
return false;
}
// 个数true
if(x / 10 < 1){
return true;
}
String curNumber = x + "";
String reversedNumber = (new StringBuilder(curNumber)).reverse().toString();
return curNumber.equals(reversedNumber);
}
}
LeetCode原题链接:leetcode-cn.com/problems/pa…