fork download
  1. public class Main {
  2.  
  3. static String testcase1 = "-2x^3+10x-4x^2";
  4. static String testcase2 = "3";
  5.  
  6. public static void main(String args[]){
  7. int result = eval(testcase1,testcase2);
  8. System.out.println("Result : "+result);
  9. }
  10.  
  11. public static int eval(String str,String valx){
  12. int sum = 0;
  13. String subStr = "";
  14.  
  15. int len = str.length();
  16. for (int i = 0; i <= len; i++)
  17. {
  18. if(i == len || str.charAt(i) == '-' || str.charAt(i) == '+')
  19. {
  20. subStr = str.substring(0, i);
  21. System.out.println("subStr="+subStr);
  22. sum += evalSubPoly(subStr, valx);
  23. if (i != len && str.charAt(i) == '+')
  24. str = str.substring(i+1);
  25. else
  26. str = str.substring(i);
  27. System.out.println(str);
  28. len = str.length();
  29. i = 0;
  30. }
  31. }
  32. return sum;
  33. }
  34.  
  35. public static int evalSubPoly(String poly,String valx){
  36. int len = poly.length();
  37. String num = "";
  38. String power = "";
  39. int exp = 0, coeff = 0;
  40.  
  41. for(int i = 0; i < len; i++)
  42. {
  43. if(poly.charAt(i) == 'x')
  44. {
  45. num = poly.substring(0, i);
  46. coeff = Integer.parseInt(num);
  47. }
  48. if(poly.charAt(i) == '^')
  49. {
  50. power = poly.substring(i+1, len);
  51. exp = Integer.parseInt(power);
  52. }
  53. }
  54.  
  55. if(power.equals(""))
  56. exp = 1;
  57. System.out.println("coeff="+coeff);
  58.  
  59. int sum = 1;
  60. int x = Integer.parseInt(valx);
  61.  
  62. for (int i = 0; i < exp; i++)
  63. {
  64. sum = sum*x;
  65. }
  66. System.out.println("sum="+sum);
  67. sum = sum*coeff;
  68.  
  69. return sum;
  70. }
  71. }
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
subStr=
coeff=0
sum=3
-2x^3+10x-4x^2
subStr=-2x^3
coeff=-2
sum=27
10x-4x^2
subStr=10x
coeff=10
sum=3
-4x^2
subStr=-4x^2
coeff=-4
sum=9

Result : -60