Skip to content

Latest commit

 

History

History

2011.Final Value of Variable After Performing Operations

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

English Version

题目描述

存在一种仅支持 4 种操作和 1 个变量 X 的编程语言:

  • ++XX++ 使变量 X 的值 1
  • --XX-- 使变量 X 的值 1

最初,X 的值是 0

给你一个字符串数组 operations ,这是由操作组成的一个列表,返回执行所有操作后, X最终值

 

示例 1:

输入:operations = ["--X","X++","X++"]
输出:1
解释:操作按下述步骤执行:
最初,X = 0
--X:X 减 1 ,X =  0 - 1 = -1
X++:X 加 1 ,X = -1 + 1 =  0
X++:X 加 1 ,X =  0 + 1 =  1

示例 2:

输入:operations = ["++X","++X","X++"]
输出:3
解释:操作按下述步骤执行: 
最初,X = 0
++X:X 加 1 ,X = 0 + 1 = 1
++X:X 加 1 ,X = 1 + 1 = 2
X++:X 加 1 ,X = 2 + 1 = 3

示例 3:

输入:operations = ["X++","++X","--X","X--"]
输出:0
解释:操作按下述步骤执行:
最初,X = 0
X++:X 加 1 ,X = 0 + 1 = 1
++X:X 加 1 ,X = 1 + 1 = 2
--X:X 减 1 ,X = 2 - 1 = 1
X--:X 减 1 ,X = 1 - 1 = 0

 

提示:

  • 1 <= operations.length <= 100
  • operations[i] 将会是 "++X""X++""--X""X--"

解法

Python3

class Solution:
    def finalValueAfterOperations(self, operations: List[str]) -> int:
        return sum(1 if s[1] == '+' else -1 for s in operations)

Java

class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int ans = 0;
        for (String s : operations) {
            ans += (s.charAt(1) == '+' ? 1 : -1);
        }
        return ans;
    }
}

TypeScript

function finalValueAfterOperations(operations: string[]): number {
    let ans = 0;
    for (let operation of operations) {
        ans += operation.includes('+') ? 1 : -1;
    }
    return ans;
}

C++

class Solution {
public:
    int finalValueAfterOperations(vector<string>& operations) {
        int ans = 0;
        for (auto s : operations) ans += (s[1] == '+' ? 1 : -1);
        return ans;
    }
};

Go

func finalValueAfterOperations(operations []string) int {
    ans := 0
    for _, s := range operations {
        if s[1] == '+' {
            ans += 1
        } else {
            ans -= 1
        }
    }
    return ans
}

...