-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet-code-q-26.java
More file actions
49 lines (37 loc) · 1.2 KB
/
leet-code-q-26.java
File metadata and controls
49 lines (37 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.HashMap;
import java.util.Map;
class Spreadsheet {
private Map<String, Integer> cellValues;
public Spreadsheet(int rows) {
// Rows are fixed at initialization, but not directly used here
this.cellValues = new HashMap<>();
}
public void setCell(String cell, int value) {
cellValues.put(cell, value);
}
public void resetCell(String cell) {
cellValues.put(cell, 0);
}
public int getValue(String formula) {
// Remove '=' from beginning
formula = formula.substring(1);
// Split by '+'
String[] operands = formula.split("\\+");
String leftOperand = operands[0];
String rightOperand = operands[1];
int result = 0;
// Process left operand
if (leftOperand.matches("\\d+")) {
result += Integer.parseInt(leftOperand);
} else {
result += cellValues.getOrDefault(leftOperand, 0);
}
// Process right operand
if (rightOperand.matches("\\d+")) {
result += Integer.parseInt(rightOperand);
} else {
result += cellValues.getOrDefault(rightOperand, 0);
}
return result;
}
}