题目地址:
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/
给定四个运算, x + + x++ x++, + + x ++x ++x, x − − x-- x−−, − − x --x −−x。给定运算的过程,问如果初值为 0 0 0,结果是什么。
代码如下:
public class Solution {
public int finalValueAfterOperations(String[] operations) {
int res = 0;
for (String s : operations) {
if (s.charAt(1) == '-') res--;
else res++;
}
return res;
}
}
时间复杂度 O ( n ) O(n) O(n)( n n n是操作次数),空间 O ( 1 ) O(1) O(1)。