bhavi
BAN USER//bodmas rule without brackets
public static void main(String args[])
{
String str = "3+2^2*5/2-1+2^2";
System.out.println(evaluate(str.replace("-", "+-").replace("+", "\\+").replace("^", "\\^").replace("*", "\\*")));
}
private static String evaluate(String str) {
if(str.contains("+"))
{
String arr[] = compute(str.replace("\\+", "+"),"\\+") ;
return calculate(arr, "+");
}
else if(str.contains("*"))
{
String arr[] = compute(str.replace("\\*", "*"),"\\*") ;
return calculate(arr, "*");
}
else if(str.contains("/"))
{
String arr[] = compute(str,"/") ;
return calculate(arr, "/");
}
else if(str.contains("^"))
{
String arr[] = compute(str.replace("\\^", "^"),"\\^") ;
//return calculate(arr, "^");
return ""+Math.pow(toInt(arr[0]), toInt(arr[1]));
}
else
return str;
}
public static String calculate(String arr[], String operator)
{
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from given file - specified by first argument
// engine.eval();
double result = toInt(arr[0]);
for(int i = 1 ; i< arr.length; i++)
{
try {
result = (Double) engine.eval(result+operator+arr[i]);
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result+"";
}
public static String[] compute(String str, String operator)
{
String[] arr = str.split(operator);
for( int i = 0; i< arr.length; i++)
{
arr[i] = evaluate(arr[i]);
}
return arr;
}
public static double toInt(String str)
{
return Double.parseDouble(str);
}
}
public void deepest() {
int h = findHeightofTree(root);
findDeepestNode(root,h, 0);
}
private void findDeepestNode(Node root, int h, int depth) {
if(root==null)
return ;
if(root.left==null && root.right==null )
{
if(depth+1 == h)
System.out.println(root.data);
}
findDeepestNode(root.left, h, depth+1);
findDeepestNode(root.right, h, depth+1);
}
private int findHeightofTree(Node root) {
if(root == null)
return 0;
return (1+Math.max(findHeightofTree(root.left), findHeightofTree(root.right)));
}
Logic is that in a sorted array, if loop occurs the last element will point somewhere in the midddle and we dont know what is the last number. So keep checking current value < next value. if this fails then make current-> next as null. This is the last element of the list.
- bhavi February 22, 2015We have originalList. Create a DupList with other as null, copy data and next.
Now loop through the Original and Dup lists:
if orig's other == null then dup's other = null;
else if orig's other == self then dup's other = self;
else
create another temp1 list = orig's head;
create another temp2 list = orig's head;
loop through temp 1 and 2, and check if temp1's next points to the orig's other
if yes then put dup's other = temp2's current pos
this will be n^2 solution.
- bhavi February 21, 2015
- bhavi March 13, 2016