1、求2+22+222+2222+22222的和?
1 package com.KiloPhone.Fouthday; 2 3 import java.util.Scanner; 4 5 /** 6 * 求2+22+222+2222+22222的和? 7 */ 8 public class TestAlgorithm { 9 public static void main(String[] args) {10 Scanner scann = new Scanner(System.in);11 // 基数12 int i = scann.nextInt();13 // 次数14 int j = scann.nextInt();15 // 中间变量16 int k = 0;17 // 和18 int sum = 0;19 20 for(int m = 1; m <= j; m++){21 k = k * 10 + i;22 sum += k;23 }24 System.out.println(sum);25 }26 }
2、Fibonacci数列:1 1 2 3 5 8 13...
(1)第一种方法:
1 class Fibonacci { 2 public static void main(String[] args) { 3 int a = 1; 4 int b = 1; 5 int c = 0; 6 7 for (int i = 3; i <= 12; i++) { 8 c = a + b; 9 a = b;10 b = c;11 }12 System.out.println(c);13 }14 }
(2)第二种方法(递归):
1 package com.kiloPhone.sixthClass; 2 3 import java.util.Scanner; 4 5 /** 6 * Fibonacci数列 7 */ 8 public class TestFibonacci { 9 10 public static int getfibonacci(int n) {11 if (n == 1 || n == 2) {12 return 1;13 }14 return getfibonacci(n - 1) + getfibonacci(n - 2);15 }16 17 /**18 * @param args19 */20 public static void main(String[] args) {21 // TODO Auto-generated method stub22 Scanner scann = new Scanner(System.in);23 System.out.println(getfibonacci(scann.nextInt()));24 }25 26 }
3、冒泡排序法
1 // 冒泡排序法 2 class BubbleSort 3 { 4 public static void bubbleSort(int[] intArr){ 5 int temp; 6 for (int i = intArr.length - 1; i > 0;i-- ) 7 { 8 boolean isSort = false; 9 for (int j = 0; j < i; j++)10 {11 if (intArr[j + 1] < intArr[j] )12 {13 temp = intArr[j];14 intArr[j] = intArr[j + 1];15 intArr[j + 1] = temp;16 isSort = true;17 }18 }19 if (!isSort)20 {21 break;22 }23 }24 }25 public static void main(String[] args) 26 {27 int[] intArray = {1,25,12,7,89,56,23,25};28 System.out.println("排序前的值:");29 for(int i : intArray)30 {31 System.out.println(i);32 }33 bubbleSort(intArray);34 System.out.println("排序后的值:");35 for(int i : intArray)36 {37 System.out.println(i);38 }39 }40 }