What is a conservative number? Let’s first understand:
According to this requirement, write the code as follows.
Solution 1: According to the definition of a conservative number, judge whether the low digit of the squared result is equal to the original number.
package Num;
/*
* 判断一个数是不是守形数
* */
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String num=sc.nextLine();
isNum(num);
}
}
public static void isNum(String num){
int n=Integer.parseInt(num);
int s=(int)Math.pow(n,2);
String s1=Integer.toString(s);
if((s1).endsWith(num)){
System.out.println("Yes!");
}else{
System.out.println("No!");
}
}
}
Solution 2: Record the number of digits n, so that the number obtained by squaring num%10^n, if the result obtained is the same as n, it is a conservative number.
code show as below:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String num=sc.nextLine();
isNum1(num);
}
}
public static void isNum1(String num){
int len=num.length();
int n=Integer.parseInt(num);
int n1=(int)Math.pow(n,2);
if(n1%Math.pow(10,len)==n){
System.out.println("Yes!");
}else {
System.out.println("No!");
}
}
}
Which method do you prefer?