Created
December 4, 2022 13:17
-
-
Save zeynep-turker/3850fc93e5a772b2b61f2a3fcddced31 to your computer and use it in GitHub Desktop.
Missing Digit Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static String MissingDigit(String str) { | |
String[] newStr = new String[2]; | |
char op = 'c'; | |
String resultValue = ""; | |
str = str.replace(" ", ""); | |
if (str.contains("+")) { | |
resultValue = str.split("=")[1]; | |
newStr = str.split("=")[0].split("\\+"); | |
op = '+'; | |
} else if (str.contains("-")) { | |
resultValue = str.split("=")[1]; | |
newStr = str.split("=")[0].split("-"); | |
op = '-'; | |
} else if (str.contains("*")) { | |
resultValue = str.split("=")[1]; | |
newStr = str.split("=")[0].split("\\*"); | |
op = '*'; | |
} else if (str.contains("/")) { | |
resultValue = str.split("=")[1]; | |
newStr = str.split("=")[0].split("/"); | |
op = '/'; | |
} | |
String result = ""; | |
int index = 0; | |
if (newStr[0].contains("x")) { | |
result = findResult(Integer.parseInt(resultValue), Integer.parseInt(newStr[1]), op, true); | |
index = newStr[0].indexOf('x'); | |
} else if (newStr[1].contains("x")) { | |
result = findResult(Integer.parseInt(resultValue), Integer.parseInt(newStr[0]), op, true); | |
index = newStr[1].indexOf('x'); | |
} else { | |
result = findResult((Integer.parseInt(newStr[0])), (Integer.parseInt(newStr[1])), op, false); | |
index = resultValue.indexOf('x'); | |
} | |
return String.valueOf(result.charAt(index)); | |
} | |
public static String findResult(int num1, int num2, char op, boolean isInverse) { | |
String result = null; | |
switch (op) { | |
case '+' -> { | |
if (isInverse) result = Integer.toString(num1 - num2); | |
else result = Integer.toString(num1 + num2); | |
} | |
case '-' -> { | |
if (isInverse) result = Integer.toString(num1 + num2); | |
else result = Integer.toString(num1 - num2); | |
} | |
case '*' -> { | |
if (isInverse) result = Integer.toString(num1 / num2); | |
else result = Integer.toString(num1 * num2); | |
} | |
case '/' -> { | |
if (isInverse) result = Integer.toString(num1 * num2); | |
else result = Integer.toString(num1 / num2); | |
} | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
Scanner s = new Scanner(System.in); | |
System.out.print(MissingDigit("1x0 * 12 = 1200")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment