方法一: 截取字符串方式
public class 立方尾不变 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count = 0;
//注意这里使用long类型,int类型立方值超出范围
for(long i = 1; i < 10000; i++) {
//获取初始值的长度
int length1 = String.valueOf(i).length();
//获取立方值的长度
int length2 = String.valueOf(i*i*i).length();
//截取字符串
String str = String.valueOf(i*i*i).substring(length2-length1);
//将字符串转为Integer类型和i进行比较
if(Integer.valueOf(str) == i) {
count++;
}
}
System.out.println(count);
}
}
方法二:分段处理方式
因为是1000以内的数字,我们可以把它分为10、100、1000、10000
public class 立方尾不变 {
public static void main(String[] args) {
int count = 0;
for(long i = 1; i < 10000; i++) {
if(i < 10) {
if(Math.pow(i, 3) % 10 == i) {
count++;
}
}else if(i < 100){
if(Math.pow(i, 3) % 100 == i) {
count++;
}
}else if(i < 1000) {
if(Math.pow(i, 3) % 1000 == i) {
count++;
}
}else if(i < 10000) {
if(Math.pow(i, 3) % 10000 == i) {
count++;
}
}
}
System.out.println(count);
}
}