复习一下数据结构的相应算法随笔记一下方便查看
一、 十进制转二进制的三种实现方式
- 利用循环求余方法
public class Main { public static void binaryToDecimal(int n){ int t = 1; //用来记录位数 int result = 0; //用来记录最后的二进制数 int r = 0; //用来存储余数 while(n != 0){ r = n % 2; n = n / 2; result += r * t; t = t * 10; } System.out.println(result); } public static void main(String[] args) { binaryToDecimal(10); } }
- java的字符串拼接法
public class Main { public static void binaryToDecimal(int n){ String str = ""; while(n!=0){ str = n%2 + str; n = n / 2; } System.out.println(str); } public static void main(String[] args) { binaryToDecimal(10); } }
- 递归实现
public class Main { public static void change(int num)//如果输入num为10 { if(num==0) { return; } else { /* 不能这样写 System.out.println(num % 2);结果是0101 从上往下 ? 在递归调用之上就是顺序输出 change(num / 2); */ change(num / 2); //先反复调用自身后一次返回 System.out.println(num % 2);//结果是1010 从下往上? 在递归调用之下就是逆序输出! } } public static void main(String[] args) { change(10); } }
二、菲波那切数列实现的两种方法
- 非递归,交替相加
public class Main { public static long Fib(long n) { if(n == 0||n == 1) { return n; } long first = 0; long second = 1; long third = 0; for(int i = 2;i <= n;i++) { third = first + second; first = second;//将second的值赋给first second = third;//将third的值赋给second } return third; } public static void main(String[] args) { System.out.println(Fib(5)); } }
2. 递归实现
public class Main { public static long Fib(long n) { if(n == 1||n == 0) { return n; } return Fib(n-1) + Fib(n-2); } public static void main(String[] args) { System.out.println(Fib(5)); } }