피보나치 수 Level 1
class Fibonacci {
public long fibonacci(int num) {
long f1 = 0;
long f2 = 1;
long f = 0;
for (int i=1; i<num; i++) { // i 가 1로 시작함에 유의!!
f = f1 + f2;
f1 = f2;
f2 = f;
}
return f;
}
// 아래는 테스트로 출력해 보기 위한 코드입니다.
public static void main(String[] args) {
Fibonacci c = new Fibonacci();
int testCase = 3;
System.out.println(c.fibonacci(testCase));
}
}
재귀 호출을 이용한 풀이(재귀호출은 자주 쓰지 않는 것이 좋음 메모리 스택을 많이 쓰기 때문)
이게 정석인줄 알았는데 아니였다!
class Fibonacci {
public long fibonacci(int num) {
long answer = 0;
if(num<2){
answer=num;
}else{
answer=fibonacci(num-1)+fibonacci(num-2);
}
return answer;
}
// 아래는 테스트로 출력해 보기 위한 코드입니다.
public static void main(String[] args) {
Fibonacci c = new Fibonacci();
int testCase = 3;
System.out.println(c.fibonacci(testCase));
}
}
'프로그래밍 > 알고리즘(자바)' 카테고리의 다른 글
약수의 합 Level 1 (0) | 2018.05.06 |
---|---|
최대값과 최소값 Level 1 (0) | 2018.05.06 |
평균구하기 Level 1 : For each문 (0) | 2018.05.06 |
문자열 내림차순으로 배치하기 Level 1 #Collections,join,sort,asList,reverse (0) | 2018.05.06 |
짝수와 홀수 Level 1 (0) | 2018.05.05 |