版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85244163
Title:Palindrome Number 9
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/palindrome-number/
1. 将数字构造成字符串,头尾指针遍历
时间复杂度:O(n),一次一层while循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 将数字构造成字符串,头尾指针遍历
* @param x
* @return
*/
public static boolean isPalindrome(int x) {
String s = x + "";
char sx[] = s.toCharArray();
int start = 0;
int end = sx.length - 1;
while (start < end) {
if (sx[start] != sx[end]) {
return false;
}
start++;
end--;
}
return true;
}
2. 通过求余和整除获取头尾两个数进行比较
时间复杂度:O(n),两次一层while循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 通过求余和整除获取头尾两个数进行比较
* @param x
* @return
*/
public static boolean isPalindrome1(int x) {
if (x < 0) {
return false;
}
int zroeCount = 1;
while(x / zroeCount >= 10) {
zroeCount *= 10;
}
while (x != 0) {
int start = x / zroeCount;
int end = x % 10;
if (start != end) {
return false;
}
x = (x % zroeCount) / 10;
zroeCount /= 100;
}
return true;
}