我有以下数字序列:
S1 = N, S2 = S1 + 1, S3 = 2*S1 + 1, S4 = S1 + 2, S5 = S2 + 1, S6 = 2*S2 + 1, S7 = S2 + 2 ...
使用ArrayDeque<E>
类,我必须编写一个程序来打印给定50
的第一个N
成员。
例子:
input 2
output 2 3 5 4 4 7 5 6 11 7 5 9 6 ...
这是我的代码。问题是我无法更新下一个S
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
public class p04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numN = scanner.nextInt();
scanner.close();
int counter = 1;
int nexS = numN;
Queue<Integer> fifty = new ArrayDeque<>();
for (int i = 0; i < 50; i++) {
if (i == 0){
fifty.add(numN);
}else {
if (counter == 1){
counter++;
numN = nexS + 1;
fifty.add(numN);
}else if (counter == 2){
counter++;
numN = (nexS * 2) + 1;
fifty.add(numN);
}else {
counter = 1;
numN = nexS +2;
fifty.add(numN);
nexS = nexS + 1;
}
}
}
for (Integer integer : fifty) {
System.out.print(integer + " ");
}
}
}
答案 0 :(得分:1)
解决这个问题的方法使用ArrayList解决它更容易。我认为我的解决方案更加面向队列,这是你的任务。所以这是我的看法:
public static void trustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
您不需要计数器,因为您已经有一个(import java.util.ArrayDeque;
import java.util.Scanner;
public class SequenceQuestion {
public static void constructSequence(int start, int seqLength) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(start);
System.out.print(start);
for (int i = 0; i < seqLength - 1; i++) {
int print = 0;
if (i % 3 == 0 && i != 0) queue.remove();
if (i % 3 == 0) {
print = queue.peek() + 1;
queue.add(print);
} else if (i % 3 == 1) {
print = queue.peek() * 2 + 1;
queue.add(print);
} else if (i % 3 == 2) {
print = queue.peek() + 2;
queue.add(print);
}
System.out.print(", " + print);
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
constructSequence(s.nextInt(), 50);
}
}
)并且如果您始终在开头检查mod 3并且如果等于0,则从队列中删除第一个元素。我发现这是你遇到麻烦的地方。