cs20s08sol3

# cs20s08sol3 - CS20S08 HW3 Solutions—May 8 2008 Q1 (int i...

This preview shows pages 1–3. Sign up to view the full content.

CS20S08- HW3 Solutions—May 8, 2008 Q1: greatestCommonDivisor(int i, int j){ if ( j == 0 ) return i; else return greatestCommonDivisor(j, i % j); } Q2: Recursive: int power(int i, int n){ if ( n == 0 ) return 1; else return ( i * power(i, n-1)); } Iterative: int power(int i, int n){ int result=1; while ( n > 0 ){ result *= i; n--; } return result; } Recursive (worst case log n): int power(int i, int n){ if ( n == 0 ) return 1; else{ int tmp = power(i, n/2); if ( n%2 == 0 ) // n is even return ( tmp * tmp ); else // n is odd return ( i * tmp * tmp ); } }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Q3: public boolean isPalindrome(String s) { if (s.length() < 2) return true; // Base case else { //check if the first and last chs are equal if (s.charAt(0) == s.charAt(s.length() - 1)) return isPalindrome(s.substring(1,s.length()-1)); else return false; } } Q4: a. -1 b. 120 c. 1 Q5: a. Yes, num must be zero or a negative number. b. No c. Yes. 0 is returned. d. Yes. -15 is returned.
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 3

cs20s08sol3 - CS20S08 HW3 Solutions—May 8 2008 Q1 (int i...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online