[문제풀이] 02-07. 점수 계산

𝒄𝒉𝒂𝒏𝒎𝒊𝒏·2023년 10월 28일
0

인프런, 자바(Java) 알고리즘 문제풀이

Array(1, 2차원 배열) - 0207. 점수 계산


🗒️ 문제


🎈 나의 풀이

	private static int solution(int n, String str) {
        int answer = 0, count = 0;
        String[] scores = str.split(" ");

        for(String s : scores) {
            if(s.equals("1")) {
                count++;
                answer += count;
            } else {
                count = 0;
            }
        }

        return answer;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        String str = sc.nextLine();
        System.out.println(solution(n, str));
    }


🖍️ 강의 풀이

    public int solution(int n, int[] arr){
		int answer=0, cnt=0;
		for(int i=0; i<n; i++){
			if(arr[i]==1){
				cnt++;
				answer+=cnt;
			}
			else cnt=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.print(T.solution(n, arr));
	}


💬 짚어가기

해당 문제는 채점 결과가 1인 경우, 누적 점수를 보관하는 변수를 하나 생성하고,
채점 결과가 0인 경우, 누적 점수를 초기화 하는 방식으로 쉽게 구현할 수 있다.

나의 풀이의 경우 split() 메소드를 통해 String 배열로 받았다.
강의 풀이의 경우 반복문을 통해 처음 입력을 nextInt()를 통해 정수로 받았다.
나머지 로직은 동일하다.

profile
𝑶𝒏𝒆 𝒅𝒂𝒚 𝒐𝒓 𝒅𝒂𝒚 𝒐𝒏𝒆.

0개의 댓글

관련 채용 정보