问题描述
输入是一系列以0结尾的正整数。我的任务是打印出该系列包含多少对等号。
例如:
输入:2 34 34 4 6 2 27 27 8 8 8 5 0
对:4个(34和34、27和27、8和8、8和8)
到目前为止,我已经提出了这个建议,但我认为我真的迷路了。
import java.util.Scanner;
public class P3_5 {
public static void main(String[]args) {
int k1 = 0;
int k2 = 0;
int pair = 0;
Scanner scan = new Scanner(system.in);
System.out.print("Input series of positive integers: ");
while (scan.nextInt() != 0) {
k1 = scan.nextInt();
k2 = scan.nextInt();
if (k1 == k2) {
pair++;
}
}
System.out.print(pair);
}
}
解决方法
您应该只在循环内请求一个新的int。在循环外请求初始int,然后在循环内请求一个int。在循环中将新的k2
放入k1
之后,将其与pair
进行比较,并可能递增k1 = k2
。然后设置func tableView(UITableView,didSelectRowAt: IndexPath)
并继续下一个循环迭代。
您可能需要查看HashMaps以便记住已经避免看到的数字,以免多次计算
,您不应立即要求输入两个数字,因为一个数字可以与其他两个数字形成一对,就像注释中已经说过的笨蛋一样。
根据您的问题,我假设一对是两个连续的相等数字。另外,一个数字可以与其他两个数字(如果有两个以上相等的连续数字)形成一对,在您的示例中为8
。
您必须以某种方式记住上一个数字,以便在每次迭代中将其与当前数字进行比较。由于一定数目可以成对出现,因此可以推断出对于 k 个连续数,对的数目为 k − 1 。因此,我们需要记录连续的等号序列的当前长度,如果将其重置为零(即当另一个数字出现时),则将其添加到对总数中:
// The total number of pairs found
int pairs = 0;
// The current number of consecutive equal numbers (always >= 1)
int sequence = 1;
// Record the previous number encountered. Since the first element of an
// array cannot be compared with the previous one (since there is none!),// we will need to start at the second element.
int last = ints[0];
// It is assumed that the length of the array is at least one. You should,// however,add code to check if the length is not zero.
for (int i = 1; i < ints.length; i++) {
// Check if the current number matches the previous one. If true,then
// our sequence of equal values increments
if (ints[i] == last) {
sequence++;
}
else {
// If the current element is not equal to the previous one,then
// our sequence of equal numbers has ended. In that case,add the
// length of the sequence minus one to the total number of pairs.
pairs += (sequence - 1);
// ...and reset the sequence length
sequence = 1;
}
// Update the previously seen number
last = ints[i];
}
我在这里使用了一个数组,但是除了使用ints[]
之外,您还可以要求用户输入一个整数。
因为您显然只需要计算连续的对即可。这意味着由于第一个8和第三个8不连续,所以8,8,8会产生[8,8]和[8,8]。您可以通过一个简单的循环来完成它。
int k = 0;
int count = 0;
int previousK = 0;
String s = "2 34 34 4 6 2 27 27 8 8 8 5 0";
Scanner input = new Scanner(s);
String pairs = "";
while ((k = input.nextInt()) != 0) {
// if current number equals previous,a pair has been found.
if (k == previousK) {
// update output string and count
pairs += k + " & " + k + ",";
count++;
}
// update previous value with this value
previousK = k;
}
// get rid of lingering ","
int len = pairs.length()-2;
System.out.println("Pairs: = " + count + " " + pairs.substring(0,len)+")");
打印
Pairs: 4 (34 & 34,27 & 27,8 & 8,8 & 8)