PAT(乙级)1106 2019数列(JAVA)

(要考虑N<4的情况)

1.题目如下:

把 2019 各个数位上的数字 2、0、1、9 作为一个数列的前 4 项,用它们去构造一个无穷数列,其中第 n(>4)项是它前 4 项之和的个位数字。例如第 5 项为 2, 因为 2+0+1+9=12,个位数是 2。

本题就请你编写程序,列出这个序列的前 n 项。

输入格式:

输入给出正整数 n(≤1000)。

输出格式:

在一行中输出数列的前 n 项,数字间不要有空格。

输入样例:

10

输出样例:

2019224758

题外话:这个数列中永远不会出现 2018,你能证明吗?

代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB

2.代码如下:

package pat_1106;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import static java.lang.Math.*;
import java.util.ArrayList;
public class TestPractice1106 {
	public static void main(String[] args) {
		var bf1=new BufferedReader(new InputStreamReader(System.in));
		try {
			String str1=bf1.readLine();
			int N=Integer.parseInt(str1);
			String temp="2019";
			ArrayList<String> list=new ArrayList<String>();
			int num=4;
			if(N<num) {
				System.out.println(temp.substring(0,N));
			}
			else {
				System.out.print(temp);
				while(num<N) {
					int sum=0;
					for(int i=temp.length()-1;i>=temp.length()-4;i--) {
						if(i==temp.length()-1) {
							sum+=Integer.parseInt(temp.substring(i));
						}
						else {
							sum+=Integer.parseInt(temp.substring(i,i+1));
						}
					}
					num++;
					temp=temp+String.valueOf(getNum(sum));
					temp=temp.substring(temp.length()-4);
					System.out.print(getNum(sum));
				}
			}
			
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		
	
	}
	static int getNum(int x) {
		int temp=x;
		int res=0;
		if(x<10) {
			return x;
		}
		else {
			while(temp>0) {
				res++;
				temp=temp/10;
			}
			int s=x%((int)pow(10,res-1));
			return s;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_panbk_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值