我已经构建了两种检查数字回文的方法。哪个效率更高?我所说的效率是指执行时间和内存分配。
首先,我将整数转换为字符串并检查它是否是回文。代码示例如下。
public class Palindrome{
/*
Function palindromeCheck
Return type boolean
Parameters characterArray
Checks character array for palindrome
*/
public static boolean palindromeCheck(char[] palinCheck){
boolean palindrome = true;
int firstLen = 0;
int secondLen = palinCheck.length - 1;
while(palindrome == true && firstLen < secondLen ){
if(palinCheck[firstLen] != palinCheck[secondLen]){
palindrome = false;
}
else{
firstLen++;
secondLen--;
}
} //end of while
return palindrome;
}
/*Main Function
Calls palinDromeCheck function
Prints results
*/
public static void main(String[] args){
int palinCheck = 1221;
String dipendra = Integer.toString(palinCheck);
char[] dipendraChar = dipendra.toCharArray();
System.out.println(palindromeCheck(dipendraChar));
}
}
第二种方法是不将其转换为字符串。
public class PalindromeNumber{
/*
Function: PalindromeCheck
parameters integer
ReturnType: boolean
Takes integer, checks if it is palindrome and returns accordingly
*/
public static boolean palindromeCheck(int number){
int firstNumber = number;
int secondNumber = 0;
while(number >= 1){
secondNumber = secondNumber* 10 + (number%10);
number = number/10;
}
return (firstNumber==secondNumber) ? true:false;
}
public static void main(String[] args){
System.out.println(palindromeCheck(111));
}
}
qq_遁去的一_1
小唯快跑啊
慕侠2389804
相关分类