gpt4 book ai didi

java - 如何对数字求和并乘以它们的序列计数(Java)?

转载 作者:行者123 更新时间:2023-12-02 12:32:25 26 4
gpt4 key购买 nike

输入来自控制台,作为一行,包含数字。每个数字后面都有一个字符(S、H、D 或 C)。需要对数字求和,并且仅当两个或多个字符连续出现时,才将总和乘以字符序列的计数。

For example, 2C 3C 5C 15S 10H 12H 2S 14D has value (2 + 3 + 5) * 3 + 15 + (10 + 12) * 2 + 2 + 14 = 105.

我只能提取和求和数字,但仅此而已。

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String[] input = br.readLine().split(" ");
int sum = 0;

for (String s : input) {
String number = s.substring(0, s.length() - 1);
sum += Integer.parseInt(number);
}
System.out.println(sum);
}

提前致谢!

最佳答案

这样就可以了

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String[] input = br.readLine().split(" ");
int sum = 0;
String tmpLetter = null;
int tmpSum = 0;
int count = 0;

for (String s : input) {
int number = Integer.parseInt(s.substring(0, s.length() - 1));
String letter = s.substring(s.length() - 1);

if(tmpLetter == null || tmpLetter.equals(letter)){
count++;
tmpSum += number;
} else {
sum += tmpSum * count;
count = 1;
tmpSum = number;
}
tmpLetter = letter;
}
sum += tmpSum * count;
System.out.println(sum);
}

关于java - 如何对数字求和并乘以它们的序列计数(Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45251026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com