LeetCode-回文数
解体思路:
①第一种:转换成字符串,使用字符串的现有api方法进行反转
②第二种:直接使用循环除余乘10方法,进行反转
涉及知识点:
循环判断,StringBuffer,int类型转String类型
第一种方式代码
class Solution {
public static boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
if ((x>=0) && (x < 10)) {
return true;
}
if (x >= 10) {
String str = String.valueOf(x);
StringBuffer sb = new StringBuffer(str);
StringBuffer reverse = sb.reverse();
if (str.equals(new String(reverse))) {
return true;
}
}
return false;
}
第一种方式改进代码
改进点: if条件判断精简
class Solution {
public static boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
if (x < 10) {
return true;
}
String str = String.valueOf(x);
StringBuffer sb = new StringBuffer(str);
StringBuffer reverse = sb.reverse();
return str.equals(reverse.toString());
}
第二种方式代码
class Solution {
public static boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
if (x < 10) {
return true;
}
return x == rev(x);
}
private static int rev(int x){
int reverse = 0;
//循环乘10
while (x !=0 ){
int a = x%10;
int newRev = reverse*10 +a;
//判断是否超出整数范围
//因为当整数溢出时,其值会被截断或变为负数,导致除以10后结果不同。这种情况下,我们可以确定反转后的数字超出了整数范围
if ((newRev/10) != reverse){
return 0;
}
reverse = newRev;
x = x/10;
}
return reverse;
}
}
问题:
1、if(0=< x < 10)该写法报错内容如下:
①error: illegal start of type
报错的写法:if(0=< x < 10)
②error: > or ‘,’ expected
报错的写法:if(0=< x && x < 10){
正确写法:if ((x>=0) && (x < 10))
2、int类型转string:String.valueOf(x)
3、error: missing return statement
缺少返回值,判断完代码语法无问题后,确认是否没有在循环外给方法一个return值