פתרונות של היום + שיעורי בית

שיעורי בית חובה לשיעור הבא

 

עמוד 177, שאלות 18,21,22

 

תשובות לשאלות שפתרנו היום

 

public static int countDigits(int num){

       int count = 0;

       while (num != 0){

              count++;

              num = num/10;

       }

       return count;

}

 

public static boolean checkFirstItems(int num,Stack<Integer> st,int count){

       Stack<Integer> tmp = new Stack<Integer>();

       int num2 = 0,num3 = 0,x;

       for (int i=0;i<count;i++){

              x = st.pop();

              tmp.push(x);

              num2 = num2*10+x;

              num3 = num3 +  x* (int)Math.pow(10, i);

       }

       while (!tmp.isEmpty())

              st.push(tmp.pop());

       return (num == num2 || num == num3);

}

 

public static boolean isNumInStack(int num,Stack<Integer> st){

             

       int count = countDigits(num);

       while (st.len() >= count){

              if (checkFirstItems(num,st,count))

                     return true;

              st.pop();

       }

       return false;

}

      

public static void hanoi(int n,char from,char to,char via){

       if (n == 1){

              System.out.println(from+" =>> "+to);

       }

       else{

              hanoi(n-1,from,via,to);

              System.out.println(from+" =>> "+to);

              hanoi(n-1,via,to,from);

       }

}

      

public static void incCharTree(BinNode<Character> t){

       if (t == null)

              return;

       char ch = t.getValue();

              if (ch == 'z')

                     ch = 'a';

              else

                     ch++;

       t.setValue(ch);

       incCharTree(t.getLeft());

       incCharTree(t.getRight());

}

      

public static <T> void printLeaves(BinNode<T> t){

       if (t == null)

              return;

       if (t.isLeaf())

              System.out.print(t.getValue()+",");

       else{

              printLeaves(t.getLeft());

              printLeaves(t.getRight());

       }

             

}

      

      

public static <T> int height(BinNode<T> t){

       if (t == null)

              return -1;

       if (t.isLeaf())

              return 0;

       else{

              return 1 + Math.max(height(t.getLeft()), height(t.getRight()));

       }

}

      

public static void main(String[] args) {

      

       hanoi(5, 'A', 'C', 'B');

      

 

}