-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomputeFibonacci.java
More file actions
80 lines (65 loc) · 2.28 KB
/
computeFibonacci.java
File metadata and controls
80 lines (65 loc) · 2.28 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
import java.util.Scanner;
public class computeFibonacci {
private static int fibCallCount = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the input for Fibonacci calculation:");
int n = sc.nextInt();
long result = fib(n);
System.out.println("Fibonacci of " + n + " is: " + result);
System.out.println("Number of times fib method was called: " + fibCallCount);
System.out.print("Reverse of 1234 is: ");
reverseDisplay(1234);
System.out.println();
System.out.print("Reverse of 'abcd' is: ");
reverseDisplay("abcd");
System.out.println();
System.out.println("Count of 'a' in 'banana' is: " + count("banana", 'a'));
System.out.println("Sum of digits of 3311 is: " + sumDigits(3311));
sc.close();
}
// Method to compute Fibonacci and count calls
private static long fib(int n) {
fibCallCount++;
if (n <= 1) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
// Recursive method to reverse display an integer
public static void reverseDisplay(int value) {
if (value < 10) {
System.out.print(value);
} else {
System.out.print(value % 10);
reverseDisplay(value / 10);
}
}
// Recursive method to reverse display a string
public static void reverseDisplay(String value) {
if (value.length() <= 1) {
System.out.print(value);
} else {
System.out.print(value.charAt(value.length() - 1));
reverseDisplay(value.substring(0, value.length() - 1));
}
}
// Recursive method to count occurrences of a character in a string
public static int count(String str, char a) {
if (str.length() == 0) {
return 0;
} else {
int count = (str.charAt(0) == a) ? 1 : 0;
return count + count(str.substring(1), a);
}
}
// Recursive method to sum the digits of a number
public static int sumDigits(long n) {
if (n == 0) {
return 0;
} else {
return (int)(n % 10) + sumDigits(n / 10);
}
}
}