import java.util.*;
class Main {
public int solution(int n,int[] arr) {
int answer = 0,count = 0;
for(int i=0; i<n; i++) {
//맞은경우, 1
if(arr[i] == 1) {
if(count == 0) {
answer += 1;
count++;
}
else {
answer += count+1;
count++;
}
}
//틀린경우, 0
else {
count = 0;
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = kb.nextInt();
}
System.out.println(T.solution(n, arr));
}
}
더 간단한 풀이
public int solution(int n,int[] arr) {
int answer = 0,count = 0;
for(int i=0; i<n; i++) {
//맞은경우, 1
if(arr[i] == 1) {
count += 1;
answer += count;
}
//틀린경우, 0
else {
count = 0;
}
}
return answer;
}
간단해 보이는 문제도 더 효율적으로 푸는 방법을 생각하자!