hye-log

[SWEA]1289번 원재의 메모리 복구하기(JAVA) 본문

CodingTest/SWEA

[SWEA]1289번 원재의 메모리 복구하기(JAVA)

iihye_ 2023. 7. 30. 02:00

0. 문제 링크

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV19AcoKI9sCFAZN 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

1. 문제 설명

1) 문자열에서 한 문자가 1이면 1 뒤에 있는 모든 문자를 0으로 변경

2) 모든 문자열이 0이 될 때까지 반복

 

2. 입출력

// input
2
0011
100

// output
#1 1
#2 2

 

3. 코드

import java.util.*;

public class swea1289 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		
		for(int t = 1; t <= T; t++) {
			int ans = 0; // 수정 횟수
			String str = sc.next(); // 메모리
			char base = '0'; // 기준 문자
			
			for(int i = 0; i < str.length(); i++) {
				if(base != str.charAt(i)) { // 연속된 두 문자가 다르면
					ans++; // 1회 수정
					base = str.charAt(i); // 기준 문자 바꾸기
				}
			}
			
			System.out.printf("#%d %d\n", t, ans);
		}
	}

}

 

실행 결과

 

4. 회고

1) 모든 문자열을 수정하기 보다 이전 문자와 현재 문자를 비교하는 방식으로 해결

2) 모든 문자열이 00....0 이 되어야 하므로 기준 문자를 '0' 으로 선언

 

5. Github

https://github.com/iihye/Algorithm/blob/main/SWEA/swea1289.java

 

728x90
Comments