总体而言这是一道水题,掌握以下规律就可以A出来了。
我刚开始的思路就是暴力求解,数字多大就循环多少次,自然当输入数据数量大数字大的时候就超时了,可以看我提交代码注释的部分就知道了
尽管有想过取余等方法优化,但是数字大的时候还是会超时,于是查找了很多资料,可以将任意数字的循环次数减小到4,因为尾数出现有规律,周期为4,如下表所示:
1(次方) | 2(次方) | 3(次方) | 4(次方) | 5(次方) | 6(次方) | 7(次方) | 8(次方) | 9(次方) | |
1(结尾) | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
2(结尾) | 2 | 4 | 8 | 6 | 2 | 4 | 8 | 6 | 2 |
3(结尾) | 3 | 9 | 7 | 1 | 3 | 9 | 7 | 1 | 3 |
4(结尾) | 4 | 6 | 4 | 6 | 4 | 6 | 4 | 6 | 4 |
5(结尾) | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 |
6(结尾) | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 |
7(结尾) | 7 | 9 | 3 | 1 | 7 | 9 | 6 | 1 | 9 |
8(结尾) | 8 | 4 | 2 | 6 | 8 | 4 | 2 | 6 | 8 |
9(结尾) | 9 | 1 | 9 | 1 | 9 | 1 | 9 | 1 | 9 |
所以就算循环的代码怎么写也难以超时了
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int num = in.nextInt();
while( num>0 )
{
int n = in.nextInt();
int single = n%10;
int loop = n%4;
if( loop==0 )
{
loop = 4;
}
int most_right = 1;
while( loop>0 )
{
most_right = most_right * single;
loop --;
}
System.out.println( most_right%10 );
// Time Limit Exceeded
// int a = in.nextInt();
// int temp = a;
// int res = 1;
// while( temp>0 )
// {
// res = res*a;
// res = res%10;
// temp --;
// }
// System.out.println( res );
num --;
}
}
}