问题:请你编写一个方法来判断一个整数是否是一个守形数,如果是输出"YES",否则输出"NO"。要求尽可能地简单和快速。
答:代码如下:
import java.lang.Math;
public class KeepFormatNumber {
public static String doJudge(int n) {
int sn =(int) Math.pow(n,2);
int len = countLength(n);
int times=1;
for(int i=0;i<len;++i){
times*=10;
}
if((sn-(sn/times)*times)==n) return "YES";
else return "NO";
}
private static int countLength(int n) {
int len=0;
while(n!=0){
n/=10;
++len;
}
return len;
}
public static void main(String[] args){
int n1 = 25;
int n2 = 125;
System.out.println("n1= "+n1+" result : "+KeepFormatNumber.doJudge(n1));
System.out.println("n2= "+n2+" result : "+KeepFormatNumber.doJudge(n2));
}
}
代码运行结果:
Lab-Computer-0db2f6:JavaExercises labuser$ javac KeepFormatNumber.java
Lab-Computer-0db2f6:JavaExercises labuser$ java KeepFormatNumber
n1= 25 result : YES
n2= 125 result : NO
Lab-Computer-0db2f6:JavaExercises labuser$