1 public static int divideint a int b
חילוק רקורסיבי : 1 דוגמא public static int divide(int a, int b) { if(b == 0) return 0; else if(a < b) return 0; else if(b == 1) return a; else return add(1, divide(sub(a, b)); } Divide(6, 3) 2 a 6 b 3 add(1, divide(sub(a, b)); add(1, 1); =2 1 Divide(3, 3) a 3 b 3 add(1, divide(sub(a, b)); add(1, 0); =1 0 Divide(0, 3) a 0 b 3
חילוק רקורסיבי : 1 דוגמא public static int divide(int a, int b) { if(b == 0) return 0; else if(a < b) return 0; else if(b == 1) return a; else return add(1, divide(sub(a, b)); } Divide(21, 10) 2 a 21 b 10 add(1, divide(sub(a, b)); add(1, 1); =2 1 Divide(11, 10) a 11 b 10 add(1, divide(sub(a, b)); add(1, 0); =1 0 Divide(1, 10) a 1 b 10
פתרון - 1 תרגיל : עם סוכם 1 פתרון public static int sum. Digit. With. Sum(int n){ return sum. Digit(Math. abs(n), 0); } public static int sum. Digit(int num, int sum) { if (num == 0) return sum; return sum. Digit(num/10, sum + (num%10)); } : ללא סוכם 2 פתרון public static int sum. Digit(int n){ if (n == 0) return 0; return sum. Digit(n/10) + (n %10); } 6
פתרון - 4 תרגיל public static boolean is. Palindrome(String pal) { boolean is. Pal = false; int length = pal. length(); if (length == 0 || length == 1) // can be “if (length <= 1)” instead is. Pal = true; else { is. Pal = (pal. char. At(0)==pal. char. At(length-1) && is. Palindrome(pal. substring(1, length-1))); } return is. Pal; } 11
קוד הדפסת הפרמוטציות של מחרוזת public static void perms(String s){ // We call the method perm(s, "") which prints // the empty string followed by each permutation // of s the empty string. perms(s, ""); } 18
קוד הדפסת הפרמוטציות של מחרוזת /** Function prints all the permutation of a string. * Note: assume the string is a set (no duplicate * chars) */ // Prints string acc followed by all permutations of // string s 1 public static void perms(String s 1, String acc){ if (s 1. length()==0) System. out. println(acc); else for (int i=0; i<s 1. length(); i=i+1) perms(delete(s 1, i), acc +s 1. char. At(i)); } 19
delete : פונק' עזר // This function returns the string s with the i-th // character removed public static String delete(String s, int i){ // Assumes that i is a position in the string return s. substring(0, i) + s. substring(i+1, s. length()); } 20
- Slides: 20