HDOJ 1061 Rightmost Digit

来源:互联网 发布:在mac上用win to go 编辑:程序博客网 时间:2024/06/07 19:14

HDOJ 1061 Rightmost Digit


总体而言这是一道水题,掌握以下规律就可以A出来了。

我刚开始的思路就是暴力求解,数字多大就循环多少次,自然当输入数据数量大数字大的时候就超时了,可以看我提交代码注释的部分就知道了

尽管有想过取余等方法优化,但是数字大的时候还是会超时,于是查找了很多资料,可以将任意数字的循环次数减小到4,因为尾数出现有规律,周期为4,如下表所示:

 1(次方)2(次方)3(次方)4(次方)5(次方)6(次方)7(次方)8(次方)9(次方)1(结尾)1111111112(结尾)2486248623(结尾)3971397134(结尾)4646464645(结尾)5555555556(结尾)6666666667(结尾)7931796198(结尾)8426842689(结尾)919191919

所以就算循环的代码怎么写也难以超时了

import java.io.*;import java.util.*;public class Main {public static void main(String[] args) {// TODO Auto-generated method stubScanner 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 --;}}}




0 0