JAva再帰加減法
3173 ワード
リストmapに交差、およびセットなどの操作を行うように設計される場合があります.
加減法の実装を参照できます
加減法の実装を参照できます
public class Test {
/**
* @param args
*/
public static final char y_all='+';
public static final char y_diff='-';
public static final char y_and='&'; //
// , 2
public static void main(String[] args) {
String s = "((1+2)-(3-4))+((0+1)-(2-1))";
String s1 ="((10+2)-3)+(5-2)";
System.out.println(getall(s1));
}
public static int getall(String rel){
//
if(rel.indexOf("(")==-1 && rel.indexOf(")")==-1 && rel.indexOf(y_all)==-1 && rel.indexOf(y_diff)==-1){
return getUser(rel);
}else{
String left = getLeft(rel);
System.out.println("left: "+left);
String right = getRight(rel);
System.out.println("right: "+right);
String op = getOP(rel);
System.out.println("op: "+op);
return Oper(getall(left), getall(right), op);
}
}
public static String getLeft(String rel){
int index=0;
int sub = getSub(rel, index);
String str = rel.substring(0,sub);
return clearK(str);
}
public static String getRight(String rel){
int index=0;
int sub = getSub(rel, index);
String str = rel.substring(sub+1);
return clearK(str);
}
public static String getOP(String rel){
int index=0;
int sub = getSub(rel, index);
String str = rel.substring(sub,sub+1);
return str;
}
public static int Oper(int left,int right,String op){
int tmp=0 ;
if(op.equals("+")){
tmp = left+right;
}else if(op.equals("-")){
tmp = left-right;
}else if(op.equals("&")){
//TODO:
}
return tmp;
}
public static int getUser(String rel){
int t =0;
if(null!=rel && !rel.isEmpty()){
t = Integer.parseInt(rel);
}
return t;
}
public static String clearK( String rel ) {
if(rel.startsWith("(") && rel.endsWith(")")){
rel = rel.substring(1,rel.length()-1);
}
return rel;
}
private static int getSub(String rel, int index) {
int sub =0;
char[] clt = rel.toCharArray();
for(int i=0;i<clt.length;i++){
char c = clt[i];
if(c=='('){
index++;
}
if(c==')'){
index--;
}
if(c==y_all){
if(index==0){
sub = i ;
break;
}
}
if(c==y_diff){
if(index==0){
sub = i ;
break;
}
}
if(c==y_and){
if(index==0){
sub = i ;
break;
}
}
}
return sub;
}
}