-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursion.java
More file actions
86 lines (80 loc) · 2.7 KB
/
Recursion.java
File metadata and controls
86 lines (80 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* @author Brianna Penkala
* This class contains methods that use recursion
*/
public class Recursion {
/** A field that initializes a LinkedList */
private final LinkedList list = new LinkedList();
/** A method that calculates the factorial of the input
* @param n the integer to be calculated
* @return the sum of the factorial
* @throws IllegalArgumentException when the inputted integer is negative
* */
public int sumDigits(int n) {
if (n < 0)
throw new IllegalArgumentException();
int sum;
if (n == 1 || n == 0)
sum = n;
else
sum = n + sumDigits(n - 1);
return sum;
}
/** A method that calculates the greatest common denominator
* @param a the first integer to be considered
* @param b the second integer to be considered
* @return the greatest common denominator
* */
public int gcd(int a, int b) {
int remainder = a % b;
int whole = a / b;
if (a == 0)
return b;
if (whole == 0)
return remainder;
if (remainder == 0)
return whole;
else
return gcd(b, remainder);
}
/** A method that calculates the greatest common denominator
* @param str the string to be analyzed
* @return true if the string is a palindrome, false otherwise
* */
public boolean isPalindrome(String str) {
if (str.length() <= 1)
return true;
if (str.charAt(0) == str.charAt(str.length() - 1))
return isPalindrome(str.substring(1, str.length() - 1));
return false;
}
/** A method that swaps every two nodes in a LinkedList
* @param head the head of the LinkedList to be rearranged
* @return the first node of the rearranged list
* */
public Node swapNodesInPairs(Node head) {
Node pointer = head;
if (pointer.getNext() != null) {
list.add(pointer.getNext().getElement());
list.add(pointer.getElement());
return swapNodesInPairs(head.getNext().getNext());
}
else {
list.add(pointer.getElement());
return list.getFirstNode();
}
}
/** A method that calculates the binomial coefficient
* @param n the number of elements
* @param k the number of items to be chosen
* @return the binomial coefficient
* @throws IllegalArgumentException when the an input is negative
* */
public int binomial(int n, int k) {
if (n < 0 || k < 0)
throw new IllegalArgumentException();
if (k == 0 || k == n)
return 1;
return binomial(n - 1, k - 1) + binomial(n - 1, k);
}
}