小红的购物车
[题目链接](https://www.nowcoder.com/practice/4580249cc50f4794944546e84c038c72)
思路
模拟题。遍历购物车中的每件商品,如果标记为 O(选择支付),就把价格累加到总金额中;标记为 X 则跳过。
需要注意的是,商品数量最多为 ,每件商品价格最高可达
,因此总金额可能超过 32 位整数范围,需要使用 64 位整型(C++ 的
long long,Java 的 long)。
代码
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
long long total = 0;
for (int i = 0; i < n; i++) {
int price;
char c;
cin >> price >> c;
if (c == 'O') {
total += price;
}
}
cout << total << endl;
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long total = 0;
for (int i = 0; i < n; i++) {
long price = sc.nextLong();
String c = sc.next();
if (c.equals("O")) {
total += price;
}
}
System.out.println(total);
}
}
复杂度分析
- 时间复杂度:
,其中
为商品数量,遍历一次即可。
- 空间复杂度:
,仅使用常数额外空间。

京公网安备 11010502036488号