public class StringOp { public static String rovescia(String s){ if (s== null || s.length()<= 1){ return s; } else{ return s.charAt(s.length() -1)+ rovescia(s.substring(0,s.length()-1)); } } public static int BinDec(String v){ if (v.equals("")) { return -1; } else { int right = v.charAt(v.length() - 1) - 48; if (v.length() == 1) { return right; } else { return (2 * BinDec(v.substring(0, v.length() - 1))) + right; } } } public static String BinSum(String v, String w){ if (v.length()== 0 || w.length() == 0){ return ""; } else{ return BinSum(v, w, 0); } } private static String BinSum(String v, String w, int rest){ if (v.length()>0 && w.length()>0){ char vl = v.charAt(v.length()-1); char wl = w.charAt(w.length()-1); int nl = vl - '0'; int ml = wl - '0'; String vr = v.substring(0,v.length()-1); String wr = w.substring(0,w.length()-1); if (rest+nl+ml == 3){ return BinSum(vr,wr,1)+'1'; } else if (rest+nl+ml == 2){ return BinSum(vr,wr,1)+'0'; } else if (rest+nl+ml == 1){ return BinSum(vr,wr,0)+'1'; } else{ return BinSum(vr,wr,0)+'0'; } } else if (v.length()==0 && w.length()>0 && rest ==1){ return BinSum("1",w,0); } else if (v.length()>0 && w.length()==0 && rest ==1){ return BinSum(v,"1",0); } else if (v.length()==0 && w.length()==0 && rest ==1){ return "1"; } else if (v.length()==0 && w.length()>0 && rest ==0){ return w; } else if (v.length()>0 && w.length()==0 && rest ==0){ return v; } else return ""; } // un altro modo per fare la somma // poiche' // x+s(y)= s(x+y) // x+0 = x // definiamo isZero(), binPred() e somma() // public static boolean isZero (String v){ if (v.length() == 0) { return true; } else if (v.charAt(0) =='1'){ return false; } else{ return isZero(v.substring(1)); } } public static String binPred (String v){ if (isZero(v)){ return v; } else if (v.charAt(v.length()-1)== '1'){ return v.substring(0,v.length()-1)+'0'; } else{ return binPred(v.substring(0,v.length()-1))+'1'; } } public static String succ(String v){ if (v.length()==0){ return "1"; } else if (v.charAt(v.length()-1)== '0'){ return v.substring(0,v.length()-1)+'1'; } else{ return succ(v.substring(0,v.length()-1))+'0'; } } public static String somma(String v, String w){ if (isZero(w)){ return v; } else { return succ(somma(v, binPred(w))); } } }