斐波那契数列算法
斐波那契数列定义:数列的第一项和第二项为1,以后各项都为前后两项之和。
根据定义设置定义前后两个变量left和right,分别用于生成下一项的两个加数。result变量是保存输出的变量值。
因此设计程序如下:
/**
* create by qsding@sina.cn
*/
package com.qsding.demo.business;
import java.util.Scanner;
import org.junit.Test;
/**
* 描述: 斐波那契数列算法<br/>
*
* @author qsding <br/>
* @dete 2018年3月17日23:51:50
*/
public class FibonacciAlgorithm {
/**
* 斐波那契数列算法
*/
@Test
public void execute() {
Scanner scan = new Scanner(System.in);
int nextInt = scan.nextInt();
int left = 0;
int right = 0;
int result = 0;
for (int i = 1; i <= nextInt; i++) {
if (i == 1 || i == 2) {
left = 1;
right = 1;
result = 1;
} else {
result = left + right;
left = result;
left = left ^ right;
right = right ^ left;
left = left ^ right;
}
System.out.print(result + " ");
}
scan.close();
}
}