https://www.acmicpc.net/problem/25709
민겸이는 1 빼기를 할 수 있는 능력을 가지고 있다. 1 빼기란, 다음의 두 연산 중 하나를 골라 수행하는 것이다.
민겸이가 최초로 가지고 있는 정수가 하나 주어질 때, 이 수를 0으로 만들기 위해 최소 몇 번의 1 빼기가 필요한지 구해보자.
입력
민겸이가 가지고 있는 정수 N이 주어진다.
출력
민겸이가 해당 수를 0으로 만들기 위해서 최소 몇 번의 1 빼기가 필요한지 출력한다.
민겸이는 두 가지 방법으로 숫자를 줄일 수 있다.
민겸이가 가진 숫자 N이 주어질 때,
이 숫자를 0으로 만들기 위한 최소 연산 횟수를 구하는 문제
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int count = 0;
while (N != 0) {
String strN = String.valueOf(N); // 문자열로 변환
if (strN.contains("1")) { // 1 포함시
// '1'을 하나 제거
int index = strN.indexOf('1'); // 가장 맨 앞의 1의 위치를 찾음
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strN.length(); i++) {
if (i != index) sb.append(strN.charAt(i)); // 해당 위치 문자열을 빼고 붙임
}
String resultStr = sb.toString().replaceFirst("^0+", ""); // 앞쪽 0 제거
N = resultStr.isEmpty() ? 0 : Integer.parseInt(resultStr);
} else {
N--; // '1'이 없으면 -1
}
count++;
}
System.out.println(count);
}
}
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int count = 0;
count를 0으로 초기화String strN = String.valueOf(N);
if (strN.contains("1")) {
1이 포함되어 있는지 확인int index = strN.indexOf('1');
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strN.length(); i++) {
if (i != index) sb.append(strN.charAt(i));
}
index를 첮음StringBuilder로 다시 이어붙임 → 1을 하나 지운 숫자가 완성됨String resultStr = sb.toString().replaceFirst("^0+", "");
^0+ → 문자열 처음부터 연속된 0 제거StringBuilder 객체인 sb를 toString()으로 문자열로 바꿈N = resultStr.isEmpty() ? 0 : Integer.parseInt(resultStr);
else {
N--;
}
N--으로 1을 빼줌