Back to Problem Solutions forum
Hello,
after putting in example imput data and going through debug mode action by action, everything seems and works okay, but it doesn't work with Test input data. What am I missing here?
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int initialNumber;
String operation = "";
int number;
int result;
boolean end = false;
initialNumber = in.nextInt();
result = initialNumber;
while(end == false) {
operation = in.next();
number = in.nextInt();
switch (operation) {
case "+":
result = result + number;
break;
case "*":
result = result * number;
break;
case "%":
result = result % number;
end = true;
break;
}
}
System.out.println(result + " ");
}
}
And another question - whenever I put input data into console and press Enter, I have to press Enter again to see the result. Is it common thing or am I missing something there as well?
Thanks!
You've missed the bit that says "though intermediate results could be very large"
Try your code with this test data
10000
* 10000
* 10000
% 7982
Using biginteger, misses the whole point of the problem, which is "modular arithmetic".
My method to perform my modular operation is as follows:
private static int ModularOperation(int startNumber, String[] split) {
int modulo = Integer.parseInt(split[split.length - 1].split(" ")[1]);
for (String string : split) {
String[] values = string.split(" ");
String operator = values[0];
int value = Integer.parseInt(values[1]);
switch ( operator ) {
case "+":
startNumber += value;
break;
case "*":
startNumber *= value;
break;
default:
startNumber %= value;
}
if ( startNumber > module && !operator.equals("%")) {
startNumber %= module;
}
}
return startNumber;
}.
If I evaluate with the following data:
initial value : 40
values to evaluate: {"+ 9", "+ 2047", "* 14", "+ 5", "+ 2199", "+ 8404", "+ 710", "+ 621", "* 331" , "+4", "+4763", "*2372", "+5", "+1", "*77", "*807", "+782", "*826", "*9"
, "*4928", "+2", "*9", "+99", "+6", "+1", "*186", "+3", "+4354", "+6592" , "+7", "+3", "+87", "+1507", "+63", "*4707", "*3", "+8", "+7", "+1810" , "*9170", "*8", "+97", "*33"
, "+10", "*88", "+2923", "*5", "+5136", "+1461", "+375", "%5591"};
When calculating all of the above, I get the result: 3883. But when I send my response it says that I am wrong and it shows me the following result: 5194. Could you correct me what part of my code I am doing wrong.
Your initial code looks less or more correct, there is no need to use BigInteger
as you did at last.
Your input data looks a bit messy, so probably there was some mistake just about parsing data.
It seems you have passed this problem anyway.