코딩테스트 풀이/JAVA
[LeetCode/Easy] 2011. Final Value of Variable After Performing Operations
무지맘
2023. 1. 11. 00:40
1. Input
1) 문자열 배열 operations
2. Output
1) operations를 모두 수행한 후의 값을 반환
- 초기 값은 0이다.
3. Constraint
1) 1 <= operations.length <= 100
2) operations의 요소는 "++X", "X++", "--X", "X--"뿐이다.
4. Example
Input: operations = ["--X","X++","X++"] -> Output: 1
설명: 0 – 1 + 1 + 1 = 1이므로 1을 반환한다.
5. Code
1) 첫 코드(2022/06/02)
int x = 0;
for(int i=0 ; i<operations.length ; i++){
if(operations[i].charAt(0) == '+') x++;
else if(operations[i].charAt(0) == '-') x--;
else{
if(operations[i].charAt(1) == '+') x++;
else if(operations[i].charAt(1) == '-') x--;
}
}
return x;
2) 좀더 줄여본 코드(2023/01/11)
int x = 0;
for(int i=0 ; i<operations.length ; i++){
if(operations[i].charAt(1) == '+') x++;
else x--;
}
return x;
- 비교 연산이 줄어드니까 확실히 모든 면에서 좋아진 성능을 보였다.