Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.Scanner;
public class DeletionsEasy {
public static void main(String[] args) {
String in = parseLine();
int count = deletionGame(in);
System.out.println(count);
}
static String parseLine() {
Scanner s = new Scanner(System.in);
String line = s.nextLine();
s.close();
line = line.replaceAll(",", "").replaceAll(" ", "");
line = line.substring(1);
return line;
}
static int deletionGame(String string) {
int moves = 0;
while (string.length() > 0) {
if (string.contains("0")) {
string = removeBeforeZero(string);
} else {
string = decreaseLargestNumber(string);
}
moves++;
//System.out.println(string);
}
return moves;
}
static String removeBeforeZero(String string) {
for (int i = string.length() - 1; i >= 0; i--) {
if (string.charAt(i) == '0') {
string = string.substring(i + 1);
i = -1;
}
}
return string;
}
static String decreaseLargestNumber(String string) {
int largest = -1;
int index = -1;
for (int i = string.length() - 1; i >= 0; i--) {
int value = Integer.parseInt("" + string.charAt(i));
if (value > largest) {
largest = value;
index = i;
}
}
if (largest % 2 == 0) {
largest -= 2;
} else {
largest -= 1;
}
string = string.substring(0, index) + largest + string.substring(index + 1);
return string;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment