(要考虑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;
}
}
}