HDOJ 1061 Rightmost Digit

1 篇文章 0 订阅

HDOJ 1061 Rightmost Digit


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

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

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

 1(次方)2(次方)3(次方)4(次方)5(次方)6(次方)7(次方)8(次方)9(次方)
1(结尾)111111111
2(结尾)248624862
3(结尾)397139713
4(结尾)464646464
5(结尾)555555555
6(结尾)666666666
7(结尾)793179619
8(结尾)842684268
9(结尾)919191919

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

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 --;
		}
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值