題目

There is a programming language with only four operations and one variable X:

++X and X++ increments the value of the variable X by 1. –X and X– decrements the value of the variable X by 1. Initially, the value of X is 0.

Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.

Example

Input: operations = ["--X","X++","X++"]
Output: 1
Explanation: The operations are performed as follows:
Initially, X = 0.
--X: X is decremented by 1, X =  0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 =  0.
X++: X is incremented by 1, X =  0 + 1 =  1.
  • 題意: 看到"+“要加1 看到”-" 要減一

解法


func finalValueAfterOperations(operations []string) int {
	res := 0
	for _, v := range operations {
		if v[1] == '-' {
			res--
		} else {
			res++
		}
	}
	return res
}
  • 加個測試,看看結果是不是如預期
import (
	"github.com/stretchr/testify/assert"
	"testing"
)

func Test_finalValueAfterOperations(t *testing.T) {

	res := finalValueAfterOperations([]string{"--X", "X++", "X++"})
	assert.Equal(t, 1, res)
}

參考連結