728x90
https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV19AcoKI9sCFAZN
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
문제)
풀이)
간단하게 생각했다!!
앞에서부터 1을 찾고, 찾으면 다음부터는 모두 그 반대로 만들어주는 것으로 짰다.
바꿔준 후 count를 하나 올려주었다.
물론, 이렇게 하면 바꿔줄 것이 많아서 데이터가 정말 많아지먄 나중엔 시간초과가 날 수 있다.
import java.util.Scanner;
public class swea1289 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T;
T=sc.nextInt();
for(int test_case = 1; test_case <= T; test_case++){
String s = sc.next();
int count = 0;
char[] arr = s.toCharArray();
for(int i =0; i<s.length(); i++) {
if(arr[i] == '1') {
arr[i] = '0';
for(int j=i+1; j<s.length(); j++) {
if(arr[j] == '1')
arr[j] = '0';
else
arr[j] = '1';
}
count += 1;
}
}
System.out.println("#"+test_case+" "+count);
}//test_case
}//main
}//class
따라서 수정해본 코드!
처음에 1을 만나면, 일단 바꿔줘야 하므로 count를 +1 한다.
그리고 그 다음부터 그 자리와 옆 자리가 다르면 +1을 계속 해주었다.
왜냐하면!
101 -> 010 -> 001 -> 000 (answer: 3)
001101-> 000010 -> 000001 -> 000000 (answer: 3)
위의 예시에서 볼 수 있듯, 옆 자리의 숫자가 나와 다른 경우에만 count가 늘어남을 알 수 있다.
따라서, 모든 수를 바꿔줄 필요 없이 내 옆자리가 나와 다른 경우를 찾아보면 된다!
import java.util.Scanner;
public class swea_1289 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T;
T=sc.nextInt();
for(int test_case = 1; test_case <= T; test_case++){
String s = sc.next();
int size = s.length();
int count=0; //횟수
if(s.startsWith("1")) {
count++;
}
for (int i = 0; i <size-1; i++) {
if(s.charAt(i) != s.charAt(i+1)) {
count++;
}
}
System.out.println("#"+test_case+" "+ count);
}//테스트 케이스
sc.close();
}//main
}
728x90
'코테 > SWEA' 카테고리의 다른 글
SWEA 2805. 농작물 수확하기(JAVA) (0) | 2022.08.12 |
---|---|
SWEA 1873. 상호의 배틀필드(JAVA) (0) | 2022.08.10 |
SWEA 1954. 달팽이 숫자(JAVA) (0) | 2022.08.08 |
SWEA 1210. Ladder1(JAVA) (0) | 2022.08.07 |
SWEA 1208. Flatten(JAVA) (0) | 2022.08.07 |