cs20s08sol3

cs20s08sol3 - CS20S08- HW3 Solutions—May 8, 2008 Q1:

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

View Full Document Right Arrow Icon
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 ); } }
Background image of page 1

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

View Full DocumentRight Arrow Icon
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.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 10/02/2009 for the course CS 20 taught by Professor Agrawal during the Spring '08 term at UCSB.

Page1 / 3

cs20s08sol3 - CS20S08- HW3 Solutions—May 8, 2008 Q1:

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online