Java經(jīng)典問(wèn)題算法(二)

/*【程序21】

*

作者 南楓題目:求1+2!+3!+...+20!的和

1.

程序分析:此程序只是把累加變成了累乘。

*/

package cn.com.flywater.FiftyAlgorthm;

public class Twenty_firstFactorialSum {

static long sum = 0;

static long fac = 0;

public static void main(String[] args) {

?? long sum = 0;

?? long fac = 1;

?? for(int i=1; i<=10; i++) {

??? fac = fac * i;

??? sum += fac;

?? }

?? System.out.println(sum);

}

}

/*

【程序22】

*

作者 南楓題目:利用遞歸方法求5!哮塞。

1.

程序分析:遞歸公式:fn=fn_1*4!

*/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Twenty_secondFactorialRecursion {

public static void main(String[] args) {

?? Scanner s = new Scanner(System.in);

?? int n = s.nextInt();

?? Twenty_secondFactorialRecursion tfr =new Twenty_secondFactorialRecursion();

?? System.out.println(tfr.recursion(n));

}

public long recursion(int n) {

?? long value = 0 ;

?? if(n ==1 || n == 0) {

??? value = 1;

?? } else if(n > 1) {

??? value = n * recursion(n-1);

?? }

?? return value;

}

}

/*

【程序23】

*

作者 :南楓題目:有5個(gè)人坐在一起坛善,問(wèn)第五個(gè)人多少歲?他說(shuō)比第4個(gè)人大2歲肆饶。問(wèn)第4個(gè)人歲數(shù)驯镊,他說(shuō)比第3個(gè)人大2歲板惑。問(wèn)第三個(gè)人冯乘,又說(shuō)比第2人大兩歲裆馒。問(wèn)第2個(gè)人喷好,說(shuō)比第一個(gè)人大兩歲梗搅。最后問(wèn)第一個(gè)人,他說(shuō)是10歲订雾。請(qǐng)問(wèn)第五個(gè)人多大洼哎?

1.

程序分析:利用遞歸的方法噩峦,遞歸分為回推和遞推兩個(gè)階段识补。要想知道第五個(gè)人歲數(shù)凭涂,需知道第四人的歲數(shù)切油,依次類推澎胡,推到第一人(10歲)攻谁,再往回推戚宦。

**/

package cn.com.flywater.FiftyAlgorthm;

public class Twenty_thirdPeopleAge {

public static void main(String[] args) {

?? int age = 10;

?? for(int i=2; i<=5; i++) {

??? age += 2;

?? }

?? System.out.println(age);

}

}

/*

【程序24】

*

作者 南楓題目:給一個(gè)不多于5位的正整數(shù)困檩,要求:一悼沿、求它是幾位數(shù)糟趾,二义郑、逆序打印出各位數(shù)字非驮。說(shuō)明: 這個(gè)算法實(shí)現(xiàn)雖然實(shí)現(xiàn)了這個(gè)功能劫笙,但不健壯填大,當(dāng)輸入字符是,會(huì)出現(xiàn)異常靴寂。

*/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Twenty_fourthNumber {

publicstatic void main(String[] args) {

?? Twenty_fourthNumber tn = newTwenty_fourthNumber();

?? Scanner s = new Scanner(System.in);

?? long a = s.nextLong();

?? if(a < 0 || a > 100000) {

??? System.out.println("Error Input,please run this program Again");

??? System.exit(0);

?? }

?? if(a >=0 && a <=9) {

??? System.out.println( a + "

是一位數(shù)");

??? System.out.println("

按逆序輸出是"+ '\n' + a);

?? } else if(a >= 10 && a<= 99) {

??? System.out.println(a + "

是二位數(shù)");

??? System.out.println("

按逆序輸出是");

??? tn.converse(a);

?? } else if(a >= 100 && a<= 999) {

??? System.out.println(a + "

是三位數(shù)");

??? System.out.println("

按逆序輸出是");

??? tn.converse(a);

?? } else if(a >= 1000 && a<= 9999) {

??? System.out.println(a + "

是四位數(shù)");

??? System.out.println("

按逆序輸出是");

??? tn.converse(a);

?? } else if(a >= 10000 && a<= 99999) {

??? System.out.println(a + "

是五位數(shù)");

??? System.out.println("

按逆序輸出是");

??? tn.converse(a);

?? }

}

public void converse(long l) {

?? String s = Long.toString(l);

?? char[] ch = s.toCharArray();

?? for(int i=ch.length-1; i>=0; i--) {

??? System.out.print(ch[i]);

?? }

}

}

這個(gè)算法實(shí)在太土了,也許只有我南楓才會(huì)這樣寫(xiě)收壕,下面寫(xiě)一個(gè)優(yōu)雅一點(diǎn)的

import java.util.Scanner;

public class Twenty_fourthNumber {

public static void main(String[] args) {

?? Twenty_fourthNumber tn = newTwenty_fourthNumber();

?? Scanner s = new Scanner(System.in);

?? long a = s.nextLong();

????? String s = Long.toString(l);

?? char[] ch = s.toCharArray();

System.out.println(a + "

是"

+ ch.length + “位數(shù)”);

?? for(int i=ch.length-1; i>=0; i--) {

??? System.out.print(ch[i]);

}

}

}

/*

【程序25】

*

作者 南楓題目:一個(gè)5位數(shù)蜜宪,判斷它是不是回文數(shù)圃验。即12321是回文數(shù),個(gè)位與萬(wàn)位相同摊聋,十位與千位相同麻裁。

**/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Twenty_fifthPalindrom {

static int[] a = new int[5];

static int[] b = new int[5];

public static void main(String[] args) {

?? boolean is =false;

?? Scanner s = new Scanner(System.in);

?? long l = s.nextLong();

?? if (l > 99999 || l < 10000) {

??? System.out.println("Input error,please input again!");

??? l = s.nextLong();

?? }

?? for (int i = 4; i >= 0; i--) {

??? a[i] = (int) (l / (long) Math.pow(10,i));

??? l =(l % ( long) Math.pow(10, i));

?? }

?? System.out.println();

?? for(int i=0,j=0; i<5; i++, j++) {

???? b[j] = a[i];

?? }

?? for(int i=0,j=4; i<5; i++, j--) {

??? if(a[i] != b[j]) {

???? is = false;

???? break;

??? } else {

???? is = true;

??? }

?? }

?? if(is == false) {

? ??System.out.println("is not aPalindrom!");

?? } else if(is == true) {

??? System.out.println("is aPalindrom!");

?? }

}

}

這個(gè)更好,不限位數(shù)

public static void main(String[] args) {

?? Scanner s = new Scanner(System.in);

?? System.out.print("

請(qǐng)輸入一個(gè)正整數(shù):");

?? long a = s.nextLong();

?? String ss = Long.toString(a);

??? char[] ch = ss.toCharArray();

??? boolean is =true;

?? int j=ch.length;

?? for(int i=0; i

?? if(ch[i]!=ch[j-i-1]){is=false;}

?? }

?? if(is==true){System.out.println("

這是一個(gè)回文數(shù)");}

???? else {System.out.println("

這不是一個(gè)回文數(shù)");}

??? }

/*

【程序26】

*

作者??南楓題目:請(qǐng)輸入星期幾的第一個(gè)字母來(lái)判斷一下是星期幾手销,如果第一個(gè)字母一樣原献,則繼續(xù) 判斷第二個(gè)字母。

1.

程序分析:用情況語(yǔ)句比較好讲仰,如果第一個(gè)字母一樣鄙陡,則判斷用情況語(yǔ)句或if語(yǔ)句判斷第二個(gè)字母趁矾。此程序雖然實(shí)現(xiàn)了基本功能毫捣,但必須嚴(yán)格按照題目的要求輸入饶辙,否則程序無(wú)法執(zhí)行

**/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Twenty_sixthWeek {

Scanner s = new Scanner(System.in);

public static void main(String[] args) {

?? Twenty_sixthWeek tw = newTwenty_sixthWeek();

?? char ch = tw.getChar();

?? switch(ch) {

??? case 'M':

???? System.out.println("Monday");

???? break;

??? case 'W':

????System.out.println("Wednesday");

???? break;

??? case 'F':

????System.out.println("Friday");

???? break;

??? case 'T': {

???? System.out.println("pleaseinput the second letter!");

???? char ch2 = tw.getChar();

???? if(ch2 == 'U'){System.out.println("Tuesday"); }

???? else if(ch2 == 'H'){System.out.println("Thursday"); }

??? };

???? break;

??? case 'S': {

???? System.out.println("pleaseinput the scecond letter!");

???? char ch2 = tw.getChar();

???? if(ch2 == 'U') {System.out.println("Sunday");}

???? else if(ch2 == 'A'){System.out.println("Saturday"); }

??? };

???? break;

?? }

}

public char getChar() {

?? String str = s.nextLine();

?? char ch = str.charAt(0);

?? if(ch<'A' || ch>'Z') {

??? System.out.println("Input error,please input a capital letter");

??? getChar();

?? }

?? return ch;

}

}

/*

【程序27】

*

作者 南楓題目:求100之內(nèi)的素?cái)?shù)

1.

程序分析:判斷素?cái)?shù)的方法:用一個(gè)數(shù)分別去除2到sqrt(這個(gè)數(shù)),如果能被整除矿微, 則表明此數(shù)不是素?cái)?shù)冷冗,反之是素?cái)?shù)蒿辙。

**/

packagecn.com.flywater.FiftyAlgorthm;

public class Twenty_seventhPrimeNumber {

public static void main(String[] args) {

?? boolean b =false;

?? int count = 0;

?? for(int i=2; i<100; i+=1) {

??? for(int j=2; j<=Math.sqrt(i); j++){

???? if(i % j == 0) {

????? b = false;

????? break;

???? } else{

????? b = true;

???? }

??? }

??? if(b == true) {

???? count ++;

???? System.out.print(i + " ");

??? }

?? }

?? System.out.println('\n' + "Thenumber of PrimeNumber is :" + count);

}

}

/*【程序28】

*

作者 南楓題目:對(duì)10個(gè)數(shù)進(jìn)行排序

1.

程序分析:可以利用選擇法,即從后9個(gè)比較過(guò)程中泰偿,選擇一個(gè)最小的與第一個(gè)元素交換耗跛, 下次類推调塌,即用第二個(gè)元素與后8個(gè)進(jìn)行比較,并進(jìn)行交換姜凄。

**/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Twehty_eighthNumberSort {

publicstatic void main(String[] args) {

?? Scanner s = new Scanner(System.in);

?? int[] a = new int[10];

?? for(int i=0; i<10; i++) {

??? a[i] = s.nextInt();

?? }

?? for(int i=0; i<10; i++) {

??? for(int j=i+1; j<10; j++) {

???? if(a[i] > a[j]) {

????? int t = a[i];

????? a[i] = a[j];

????? a[j] = t;

???? }

??? }

?? }

?? for(int i=0; i<10; i++) {

??? System.out.print(a[i] + "");

?? }

}

}

/*

【程序29】

*

作者???南楓

*

按程序分析态秧,好像只是求主對(duì)角線的和題目:求一個(gè)3*3矩陣對(duì)角線元素之和

1.

程序分析:利用雙重for循環(huán)控制輸入二維數(shù)組愤诱,再將a[i][i]累加后輸出。

**/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Twenty_ninthCrossSum {

publicstatic void main(String[] args) {

?? Scanner s = new Scanner(System.in);

?? int[][] a = new int[3][3];

?? for(int i=0; i<3; i++) {

??? for(int j=0; j<3; j++) {

???? a[i][j] = s.nextInt();

??? }

?? }

?? System.out.println("

輸入的3

* 3 矩陣是:");

?? for(int i=0; i<3; i++) {

??? for(int j=0; j<3; j++) {

???? System.out.print(a[i][j] + "");

??? }

??? System.out.println();

?? }

?? int sum = 0;

?? for(int i=0; i<3; i++) {

??? for(int j=0; j<3; j++) {

???? if(i == j) {

????? sum += a[i][j];

???? }

??? }

?? }

?? System.out.println("

對(duì)角線和是" + sum);

}

}

/*

【程序30】

*

作者 南楓題目:有一個(gè)已經(jīng)排好序的數(shù)組〕睿現(xiàn)輸入一個(gè)數(shù),要求按原來(lái)的規(guī)律將它插入數(shù)組中变隔。

1.

程序分析:首先判斷此數(shù)是否大于最后一個(gè)數(shù)匣缘,然后再考慮插入中間的數(shù)的情況肌厨,插入后此元素之后的數(shù),依次后移一個(gè)位置表鳍。

**/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class ThirtiethInsert {

public static void main(String[] args) {

?? int[] a = new int[]{1, 2, 3, 4, 5, 6,7};

?? int[] b = new int[a.length+1];

?? int t1 =0, t2 = 0;?????????????????????????????????????????

?? int i =0;

?? Scanner s= new Scanner(System.in);

?? int num = s.nextInt();

?? /*

?? *

定義兩個(gè)數(shù)組a譬圣,b,一個(gè)a的長(zhǎng)度比另一個(gè)b大1盯漂,a看做是

?? *

已經(jīng)排好序的就缆。

?? *

接下來(lái)的過(guò)程是

?? * 1:

如果num比最后一個(gè)數(shù)大竭宰,把num賦值給數(shù)組b的最后一個(gè)數(shù)

?? *???

再按順序把a(bǔ)的每個(gè)元素賦給b

?? * 2:

否則(num不比a 的最后一個(gè)數(shù)大)切揭,

?? *????

如果a的元素比num 小廓旬,則將這些元素按順序賦給b

?? *????

將num賦給比num大的b數(shù)組的元素孕豹,

?? *????

跳出第一個(gè)for循環(huán)春霍。

?? * 3:

定義一個(gè)循環(huán)控制變量址儒,從num傳給數(shù)組后num的下標(biāo)值加一開(kāi)始离福;

?? *???

直到b的結(jié)尾,將剩下的a的值賦給b,賦值的過(guò)程是b[j]= a[i-1];

?? *???

?? */

?? if(num >= a[a.length-1]) {

??? b[b.length-1] = num;

??? for(i=0; i

???? b[i] = a[i];

??? }

?? } else {

??? for(i=0; i

???? if(num >= a[i]) {

????? b[i] = a[i];

? ???} else {???

????? b[i] = num;

????? break;

???? }

??? }

??? for(int j=i+1; j

???? b[j] = a[j-1];

??? }

?? }

?? for (i = 0; i < b.length; i++) {

??? System.out.print(b[i] + "");

?? }

}

}

/*

【程序21】

*

作者 南楓題目:求1+2!+3!+...+20!的和

1.

程序分析:此程序只是把累加變成了累乘絮识。

*/

package cn.com.flywater.FiftyAlgorthm;

public class Twenty_firstFactorialSum {

static long sum = 0;

static long fac = 0;

public static void main(String[] args) {

?? long sum = 0;

?? long fac = 1;

?? for(int i=1; i<=10; i++) {

??? fac = fac * i;

??? sum += fac;

?? }

?? System.out.println(sum);

}

}

/*

【程序32】

*

作者??南楓題目:取一個(gè)整數(shù)a從右端開(kāi)始的4~7位。程序分析:可以這樣考慮:

(1)

先使a右移4位彼念。

(2)

設(shè)置一個(gè)低4位全為1,其余全為0的數(shù)哲思∨锱猓可用~(~0< <4)

(3)

將上面二者進(jìn)行&運(yùn)算靠益。

**/

/*

這個(gè)題我不會(huì)做,如有高手路過(guò)壳快,還望指點(diǎn)

*

*/

package cn.com.flywater.FiftyAlgorthm;

public class Thirty_secondFS {

public static void main(String[] args) {

}

}

我沒(méi)有用提示的方法何暇,采用了字串截取裆站。

public static void main(String[] args) {

?? Scanner s = new Scanner(System.in);

?? boolean is =true;

?? System.out.print("

請(qǐng)輸入一個(gè)7位以上的正整數(shù):");

?? long a = s.nextLong();

?? String ss = Long.toString(a);

?? char[] ch = ss.toCharArray();

?? int j=ch.length;

?? if (j<7){System.out.println("

輸入錯(cuò)誤羽嫡!");}

?? else {

?? System.out.println("

截取從右端開(kāi)始的4~7位是:"+ch[j-7]+ch[j-6]+ch[j-5]+ch[j-4]);

?? }

?? }

【程序33】

*

作者??南楓題目:打印出楊輝三角形(要求打印出10行如下圖)

1.

程序分析:

??????? 1

?????? 1 1

????? 1 2 1

???? 1 3 3 1

??? 1 4 6 4 1

?? 1 5 10 10 5 1

*/

/*

*

網(wǎng)上千篇一律是這種寫(xiě)法杭棵,我也沒(méi)有什么創(chuàng)新,

* a[i][j]=a[i-1][j]+a[i-1][j-1]

就是這個(gè)程序的核心

*

定義的是二維數(shù)組滓侍,為了使輸出的結(jié)果看起來(lái)漂亮一點(diǎn)

*

可以用for(int

k=0; k<2*(10-i)-1; k++)控制輸出的空格

*

這個(gè)循環(huán)是在控制行數(shù)的循環(huán)里面捺球,控制列數(shù)的循環(huán)外面氮兵。

*

記得在輸出菱形時(shí)為了控制下半部分的輸出胆剧,在下拼命的寫(xiě)出

* for(int k=1; k<=WIDTH-2*i-1; k++)

才算了事铃绒。

*/

package cn.com.flywater.FiftyAlgorthm;

public class Thirty_thirdYangTriangle {

public static void main(String[] args) {

?? int[][] a = new int[10][10];

?? for(int i=0; i<10; i++) {

??? a[i][i] = 1;

??? a[i][0] = 1;

?? }

?? for(int i=2; i<10; i++) {

??? for(int j=1; j

???? a[i][j] = a[i-1][j-1] + a[i-1][j];

??? }

?? }

?? for(int i=0; i<10; i++) {

??? for(int k=0; k<2*(10-i)-1; k++) {

???? System.out.print(" ");

??? }

??? for(int j=0; j<=i; j++) {

???? System.out.print(a[i][j] +"?? ");

??? }

??? System.out.println();

?? }

}

}

/*

【程序34】

*

作者???南楓題目:輸入3個(gè)數(shù)a,b,c,按大小順序輸出赔癌。

1.

程序分析:利用指針?lè)椒ā?/p>

*/

/*

*

可惜灾票,Java好像沒(méi)有指針

*/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Thirty_forthCompare {

public static void main(String[] args) {

?? Scanner s = new Scanner(System.in);

?? int a = s.nextInt();

?? int b = s.nextInt();

?? int c = s.nextInt();

?? if(a < b) {

??? int t = a;

??? a = b;

??? b = t;

?? }

?? if(a < c) {

??? int t = a;

??? a = c;

??? c = t;

?? }

?? if(b < c) {

??? int t = b;

??? b = c;

??? c = t;

?? }

?? System.out.println("

從大到小的順序輸出:");

?? System.out.println(a + " " +b + " " + c);

}

}

/*

【程序35】

*

作者 南楓題目:輸入數(shù)組,最大的與第一個(gè)元素交換,最小的與最后一個(gè)元素交換婴氮,輸出數(shù)組主经。

**/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Thirty_fifthSwop {

static final int N = 8;

public static void main(String[] args) {

?? int[] a = new int [N];

?? Scanner s = new Scanner(System.in);

?? int index1 = 0, index2 = 0;

?? System.out.println("please inputnumbers");

?? for(int i=0; i

??? a[i] = s.nextInt();

??? System.out.print(a[i] + "");

?? }

?? int max =a[0], min = a[0];

?? for(int i=0; i

??? if(a[i] > max) {

???? max = a[i];

???? index1 = i;

??? }

??? if(a[i] < min) {

???? min = a[i];

???? index2 = i;

??? }

?? }

?? if(index1 != 0) {

??? int temp = a[0];

??? a[0] = a[index1];

??? a[index1] = temp;

?? }

?? if(index2 != a.length-1) {

??? int temp = a[a.length-1];

??? a[a.length-1] = a[index2];

??? a[index2] = temp;

?? }

?? System.out.println("afterswop:");

?? for(int i=0; i

??? System.out.print(a[i] + "");

?? }

}

}

/*

【程序36】

*

作者???南楓題目:有n個(gè)整數(shù)蜈块,使其前面各數(shù)順序向后移m個(gè)位置鉴腻,最后m個(gè)數(shù)變成最前面的m個(gè)數(shù)

**/

/*

*

這個(gè)題不知道有什么好辦法迷扇,比較直接方法的是把這個(gè)數(shù)組分成兩個(gè)數(shù)組,

*

再將兩個(gè)數(shù)組合起來(lái)爽哎,但如果不控制好數(shù)組的下標(biāo)蜓席,就會(huì)帶來(lái)很多麻煩。

*/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Thirty_sixthBackShift {

public static final int N =10;

public static void main(String[] args) {

?? int[] a = new int[N];

?? Scanner s = new Scanner(System.in);

?? System.out.println("please inputarray a, ten numbers:");

?? for(int i=0; i

??? a[i] = s.nextInt();

?? }

?? System.out.println("please inputm , one number:");

?? int m = s.nextInt();

?? int[] b = new int[m];

?? int[] c = new int[N-m];

?? for(int i=0; i

??? b[i] = a[i];

?? }

?? for(int i=m,j=0; i

??? c[j] = a[i];

?? }

?? for(int i=0; i

??? a[i] = c[i];

?? }

?? for(int i=m,j=0; i

??? a[i] = b[j];

?? }

?? for(int i=0; i

??? System.out.print(a[i] + "");

?? }

}

}

/*

【程序37】

*

作者 南楓題目:有n個(gè)人圍成一圈厨内,順序排號(hào)。從第一個(gè)人開(kāi)始報(bào)數(shù)(從1到3報(bào)數(shù))渺贤,凡報(bào)到3的人退出圈子雏胃,問(wèn)最后留下的是原來(lái)第幾號(hào)的那位。

**/

/*

*

這個(gè)程序是完全抄別人的

*/

package cn.com.flywater.FiftyAlgorthm;

import java.util.Scanner;

public class Thirty_sevenCount3Quit {

public static void main(String[] args) {

?? Scanner s = new Scanner(System.in);

?? int n = s.nextInt();

?? boolean[] arr = new boolean[n];

?? for(int i=0; i

??? arr[i] = true;//

下標(biāo)為TRUE時(shí)說(shuō)明還在圈里

?? }

?? int leftCount = n;

?? int countNum = 0;

?? int index = 0;

?? while(leftCount > 1) {

??? if(arr[index] == true) {//

當(dāng)在圈里時(shí)

???? countNum ++; //

報(bào)數(shù)遞加

???? if(countNum == 3) {//

報(bào)道3時(shí)

????? countNum =0;//

從零開(kāi)始繼續(xù)報(bào)數(shù)

????? arr[index] = false;//

此人退出圈子

????? leftCount --;//

剩余人數(shù)減一

???? }

??? }

??? index ++;//

每報(bào)一次數(shù)志鞍,下標(biāo)加一

??? if(index == n) {//

是循環(huán)數(shù)數(shù)瞭亮,當(dāng)下標(biāo)大于n時(shí),說(shuō)明已經(jīng)數(shù)了一圈固棚,

???? index = 0;//

將下標(biāo)設(shè)為零重新開(kāi)始统翩。

??? }

?? }

?? for(int i=0; i

??? if(arr[i] == true) {

???? System.out.println(i);

??? }

?? }

}

}

/*

【程序38】

*

作者 南楓題目:寫(xiě)一個(gè)函數(shù),求一個(gè)字符串的長(zhǎng)度此洲,在main函數(shù)中輸入字符串厂汗,并輸出其長(zhǎng)度。

*/

package cn.com.flywater.FiftyAlgorthm;

public class Thirty_eighthStringLength {

public static void main(String[] args) {

?? String s = "jdfifdfhfhuififffdfggee";

?? System.out.print("

字符串的長(zhǎng)度是:");

?? System.out.println(s.length());

}

}

*

【程序39】

*

作者???南楓題目:編寫(xiě)一個(gè)函數(shù)呜师,輸入n為偶數(shù)時(shí)娶桦,調(diào)用函數(shù)求1/2+1/4+...+1/n,

當(dāng)輸入n為奇數(shù)時(shí),調(diào)用函數(shù)1/1+1/3+...+1/n(利用指針函數(shù))

**/

package cn.com.flywater.FiftyAlgorthm;

import java.text.DecimalFormat;

import java.util.*;

public class Thirty_ninthFactionSum {

public static void main(String[] args) {

?? Scanner s = new Scanner(System.in);

?? int n = s.nextInt();

?? DecimalFormat df = newDecimalFormat("#0.00000");

?? System.out.println( n +" ****result " + df.format(sum(n)));

}

public static double sum(int n) {

?? double result = 0;

?? if(n % 2 == 0) {

??? for(int i=2; i<=n; i+=2) {

???? result += (double)1 / n;

??? }

?? } else {

??? for(int i=1; i<=n; i+=2) {

???? result += (double)1 / i ;

??? }

?? }

?? return result;

}

}

/*

【程序40】

*

作者??南楓題目:字符串排序匣掸。

**/

package cn.com.flywater.FiftyAlgorthm;

public class FortiethStringSort {

publicstatic void main(String[] args) {

?? String temp = null;

?? String[] s = new String[5];

?? s[0] ="china".toLowerCase();

??s[1] = "apple".toLowerCase();

?? s[2] ="MONEY".toLowerCase();

?? s[3] = "BOOk".toLowerCase();

?? s[4] = "yeah".toLowerCase();

?? /*

?? for(int i=0; i

??? for(int j=i+1; j

???? if(s[i].compareToIgnoreCase(s[j])> 0) {

? ????temp = s[i];

????? s[i] = s[j];

????? s[j] = temp;

???? }

??? }

?? }*/

?? for(int i=0; i

??? for(int j=i+1; j

???? if(compare(s[i], s[j]) == false) {

????? temp = s[i];

????? s[i] = s[j];

????? s[j] = temp;

???? }

? ??}

?? }

?? for(int i=0; i

??? System.out.println(s[i]);

?? }

}

static boolean compare(String s1, String s2) {

?? boolean result = true;

?? for(int i=0; i

??? if(s1.charAt(i) > s2.charAt(i)) {

???? result = false;

???? break;

??? } else if(s1.charAt(i)

???? result = true;

???? break;

??? } else {

???? if(s1.length() < s2.length()) {

????? result = true;

???? } else {

????? result = false;

???? }

??? }

?? }

?? return result;

}

}

LinkedList

類里面較重要的方法就是"addBefore(){}"和"privatevoid remove(DNode curr){}"

很多方法都與它倆有關(guān)系!!

下面的代碼是個(gè)雙向循環(huán)鏈表,在LinkedList里抄的...

package LinkedList;

import java.util.Iterator;

import java.util.ListIterator;

import java.util.NoSuchElementException;

public class MyLinkedList {

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? private DNode header;

??? private int listSize;

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? public MyLinkedList() {

??????? header = new DNode();

??????? listSize = 0;

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? private static class DNode {

??????? T nodeValue;

??????? DNode prev;

??????? DNode next;

??????? public DNode() { // for header

??????????? nodeValue = null;

??????????? prev = this; // left

??????????? next = this; // right

?? ?????}

??????? public DNode(T item) {

??????????? nodeValue = item;

??????????? prev = this;

??????????? next = this;

??????? }

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? public boolean isEmpty() {

??????? return (header.prev == header ||header.next == header);

??? }

??? public int size() {

??????? return listSize;

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? private DNodeaddBefore(DNode curr, T item) {

??????? DNode newNode, prevNode;

??????? newNode = newDNode(item);

???? ???prevNode = curr.prev;

??????? newNode.prev = prevNode;

??????? newNode.next = curr;

??????? prevNode.next = newNode;

??????? curr.prev = newNode;

??????? return newNode;

??? }

??? public boolean add(T item) {

??????? addBefore(header, item);

??????? listSize++;

??????? return true;

??? }

??? public void addFirst(T item) {

??????? addBefore(header.next, item);

??????? listSize++;

??? }

??? public void addLast(T item) {

??????? addBefore(header, item);

??????? listSize++;

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? private void remove(DNodecurr) {

??????? if(curr.next == curr) return;

??????? DNode prevNode =curr.prev, nextNode = curr.next;

??????? prevNode.next = nextNode;

??????? nextNode.prev= prevNode;

??? }

??? public boolean remove(Object o) {

??????? for(DNode p =header.next; p != header; p = p.next) {

??????????? if(o.equals(p.nodeValue)) {

??????????????? remove(p);

??????????????? listSize--;

??????????????? return true;

??????????? }

??????? }

???????return false;

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? public void printList() {

??????? for(DNode p =header.next; p != header; p = p.next)

???????????System.out.println(p.nodeValue);

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? private class MyIterator implementsIterator {

??????? public DNode nextNode =header.next;

??????? public DNodelastReturned = header;

??????? public boolean hasNext() {

??????????? return nextNode != header;

??????? }

??????? public T next() {

??????????? if(nextNode == header)

??????????????? throw newNoSuchElementException("");

??????????? lastReturned = nextNode;

??????????? nextNode = nextNode.next;

??????????? returnlastReturned.nodeValue;

??????? }

??????? public void remove() {

??????????? if(lastReturned == header)

??????????????? throw newIllegalStateException("");

???????????MyLinkedList.this.remove(lastReturned);

??????????? lastReturned = header;

??????????? listSize--;

??????? }

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? private class MyListIterator extendsMyIterator implements ListIterator {

??????? private int nextIndex;

??????? MyListIterator(int index) {

??????????? if(index < 0 || index >listSize)

??????????????? throw newIndexOutOfBoundsException("");

??????????? //

如果index小于listSize/2趟紊,就從表頭開(kāi)始查找定位氮双,否則就從表尾開(kāi)始查找定位

??????????? if(index < (listSize>> 1)) {

??????????????? nextNode = header.next;

??????????????? for(nextIndex = 0;nextIndex < index; nextIndex++)

??????????????????? nextNode =nextNode.next;

??????????? }else {

??????????????? nextNode = header;

??????????????? for(nextIndex = listSize;nextIndex > index; nextIndex--)

??????????????????? nextNode =nextNode.prev;

??????????? }

??????? }

??????? public boolean hasPrevious() {

??????????? return nextIndex != 0;

??????????? //return nextNode.prev !=header;

??????? }

??????? public T previous() {

??????????? if (nextIndex == 0)

??????????????? throw newNoSuchElementException("no");

??????????? lastReturned = nextNode =nextNode.prev;

??????????? nextIndex--;

??????????? returnlastReturned.nodeValue;

??????? }

??????? public void remove() {

??????????? if(lastReturned == header)

??????????????? throw newIllegalStateException("");

???????????MyLinkedList.this.remove(lastReturned);

??????????? nextIndex--;

??????????? listSize--;

??????????? if(lastReturned == nextNode)

??????????????? nextNode = nextNode.next;

??????????? lastReturned = header;

??????? }

??????? public void add(T item) {

???????????MyLinkedList.this.addBefore(nextNode, item);

??????????? nextIndex++;

??????????? listSize++;

??????????? lastReturned = header;

??????? }

??????? public void set(T item) {

???????????? if (lastReturned == header)

???????????????? throw newIllegalStateException();

???????????? lastReturned.nodeValue =item;

??????? }

??????? public int nextIndex() {

??????????? return nextIndex;

??????? }

??????? public int previousIndex() {

?? ?????????return nextIndex - 1;

??????? }

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? public Iterator iterator() {

??????? return new MyIterator();

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? public ListIteratorlistIterator(int index) {

? ??????return new MyListIterator(index);

??? }

??? //

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

??? public static void main(String[]args) {

??????? MyLinkedList t =new MyLinkedList();

??????? t.add("A");

??????? t.add("B");

??????? t.add("C");

????? ??t.add("D");

??????? //t.remove("B");

??????? //t.addFirst("AA");

??????? //t.addLast("BB");

??????? //t.printList();

??????? ListIterator it =t.listIterator(t.size());

??????? while(it.hasPrevious()) {

??????????? System.out.println(it.previous());// D C B A

??????? }

??? }

}// MyLinkedList end

ArrayList

底層數(shù)組實(shí)現(xiàn)的,當(dāng)實(shí)例化一個(gè)ArrayList是也相當(dāng)實(shí)例化了一個(gè)數(shù)組所以對(duì)元素的隨即訪問(wèn)較快,而增加刪除操作慢

LinkedList

底層實(shí)現(xiàn)是一個(gè)雙向鏈表,沒(méi)一個(gè)結(jié)點(diǎn)都包含了前一個(gè)元素的引用和后一個(gè)元素的引用和結(jié)點(diǎn)值所以對(duì)元素的隨即訪問(wèn)很慢,而增刪較快

java

實(shí)現(xiàn)鏈表和c實(shí)現(xiàn)一樣碰酝。就是指針變成了引用〈鞑睿【參考資料】JAVA的鏈表(2009-05-11

01:35:49)標(biāo)簽:java鏈表??分類:學(xué)習(xí)資料又是個(gè)不錯(cuò)的地方:http://blog.sina.com.cn/s/articlelist_1282789430_0_1.html

鏈表是一種重要的數(shù)據(jù)結(jié)構(gòu)送爸,在程序設(shè)計(jì)中占有很重要的地位。C語(yǔ)言和C++語(yǔ)言中是用指針來(lái)實(shí)現(xiàn)鏈表結(jié)構(gòu)的暖释,由于Java語(yǔ)言不提供指針袭厂,所以有人認(rèn)為在Java語(yǔ)言中不能實(shí)現(xiàn)鏈表,其實(shí)不然球匕,Java語(yǔ)言比C和C++更容易實(shí)現(xiàn)鏈表結(jié)構(gòu)纹磺。Java語(yǔ)言中的對(duì)象引用實(shí)際上是一個(gè)指針(本文中的指針均為概念上的意義,而非語(yǔ)言提供的數(shù)據(jù)類型)亮曹,所以我們可以編寫(xiě)這樣的類來(lái)實(shí)現(xiàn)鏈表中的結(jié)點(diǎn)橄杨∶刂ⅲ  class Node

  {

  Object data;

  Node next;//指向下一個(gè)結(jié)點(diǎn)  }

  將數(shù)據(jù)域定義成Object類是因?yàn)镺bject類是廣義超類,任何類對(duì)象都可以給其賦值式矫,增加了代碼的通用性乡摹。為了使鏈表可以被訪問(wèn)還需要定義一個(gè)表頭,表頭必須包含指向第一個(gè)結(jié)點(diǎn)的指針和指向當(dāng)前結(jié)點(diǎn)的指針采转。為了便于在鏈表尾部增加結(jié)點(diǎn)聪廉,還可以增加一指向鏈表尾部的指針,另外還可以用一個(gè)域來(lái)表示鏈表的大小故慈,當(dāng)調(diào)用者想得到鏈表的大小時(shí)板熊,不必遍歷整個(gè)鏈表。下圖是這種鏈表的示意圖:  鏈表的數(shù)據(jù)結(jié)構(gòu)  我們可以用類List來(lái)實(shí)現(xiàn)鏈表結(jié)構(gòu)察绷,用變量Head邻邮、Tail、Length克婶、Pointer來(lái)實(shí)現(xiàn)表頭筒严。存儲(chǔ)當(dāng)前結(jié)點(diǎn)的指針時(shí)有一定的技巧,Pointer并非存儲(chǔ)指向當(dāng)前結(jié)點(diǎn)的指針情萤,而是存儲(chǔ)指向它的前趨結(jié)點(diǎn)的指針,當(dāng)其值為null時(shí)表示當(dāng)前結(jié)點(diǎn)是第一個(gè)結(jié)點(diǎn)鸭蛙。那么為什么要這樣做呢?這是因?yàn)楫?dāng)刪除當(dāng)前結(jié)點(diǎn)后仍需保證剩下的結(jié)點(diǎn)構(gòu)成鏈表筋岛,如果Pointer指向當(dāng)前結(jié)點(diǎn)娶视,則會(huì)給操作帶來(lái)很大困難。那么如何得到當(dāng)前結(jié)點(diǎn)呢睁宰,我們定義了一個(gè)方法cursor(),返回值是指向當(dāng)前結(jié)點(diǎn)的指針肪获。類List還定義了一些方法來(lái)實(shí)現(xiàn)對(duì)鏈表的基本操作,通過(guò)運(yùn)用這些基本操作我們可以對(duì)鏈表進(jìn)行各種操作柒傻。例如reset()方法使第一個(gè)結(jié)點(diǎn)成為當(dāng)前結(jié)點(diǎn)孝赫。insert(Object

d)方法在當(dāng)前結(jié)點(diǎn)前插入一個(gè)結(jié)點(diǎn),并使其成為當(dāng)前結(jié)點(diǎn)红符。remove()方法刪除當(dāng)前結(jié)點(diǎn)同時(shí)返回其內(nèi)容青柄,并使其后繼結(jié)點(diǎn)成為當(dāng)前結(jié)點(diǎn),如果刪除的是最后一個(gè)結(jié)點(diǎn)预侯,則第一個(gè)結(jié)點(diǎn)變?yōu)楫?dāng)前結(jié)點(diǎn)致开。  鏈表類List的源代碼如下:  import java.io.*;

  public class List

  {

    private Node Head=null;

  private Node Tail=null;

  private Node Pointer=null;

  private int Length=0;

  public void deleteAll()

    {

  Head=null;

  Tail=null;

  Pointer=null;

  Length=0;

  }

  public void reset()

    {

  Pointer=null;

  }

  public boolean isEmpty()

    {

  return(Length==0);

  }

  public boolean isEnd()

    {

  if(Length==0)

   throw newjava.lang.NullPointerException();

  else if(Length==1)

   return true;

  else

   return(cursor()==Tail);

  }

  public Object nextNode()

    {

  if(Length==1)

   throw newjava.util.NoSuchElementException();

  else if(Length==0)

   throw newjava.lang.NullPointerException();

  else

  {

   Node temp=cursor();

   Pointer=temp;

   if(temp!=Tail)

    return(temp.next.data);

   else

    throw newjava.util.NoSuchElementException();

  }

  }

  public Object currentNode()

    {

  Node temp=cursor();

  return temp.data;

  }

    public void insert(Object d)

    {

  Node e=new Node(d);

  if(Length==0)

  {

   Tail=e;

   Head=e;

  }

  else

  {

   Node temp=cursor();

   e.next=temp;

   if(Pointer==null)

    Head=e;

   else

    Pointer.next=e;

  }

  Length++;

  }

  public int size()

    {

  return (Length);

  }

  public Object remove()

    {

  Object temp;

  if(Length==0)

   throw newjava.util.NoSuchElementException();

  else if(Length==1)

  {

   temp=Head.data;

   deleteAll();

  }

  else

  {

   Node cur=cursor();

   temp=cur.data;

   if(cur==Head)

    Head=cur.next;

   else if(cur==Tail)

   {

    Pointer.next=null;

    Tail=Pointer;

    reset();

   }

   else

    Pointer.next=cur.next;

    Length--;

  }

  return temp;

  }

  private Node cursor()

    {

  if(Head==null)

   throw newjava.lang.NullPointerException();

  else if(Pointer==null)

   return Head;

  else

   return Pointer.next;

  }

  public static void main(String[] args)

    {

  List a=new List ();

  for(int i=1;i<=10;i++)

   a.insert(new Integer(i));

   System.out.println(a.currentNode());

   while(!a.isEnd())

    System.out.println(a.nextNode());

    a.reset();

    while(!a.isEnd())

    {

     a.remove();

    }

    a.remove();

    a.reset();

    if(a.isEmpty())

     System.out.println("There is noNode in List \n");

     System.in.println("You can pressreturn to quit\n");

    try

    {

     System.in.read();

     //確保用戶看清程序運(yùn)行結(jié)果    }

    catch(IOException e)

    {}

   }

  }

  class Node

    {

   Object data;

   Node next;

   Node(Object d)

   {

    data=d;

    next=null;

   }

  }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末萎馅,一起剝皮案震驚了整個(gè)濱河市双戳,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌糜芳,老刑警劉巖飒货,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件千诬,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡膏斤,警方通過(guò)查閱死者的電腦和手機(jī)徐绑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)莫辨,“玉大人傲茄,你說(shuō)我怎么就攤上這事【诎瘢” “怎么了盘榨?”我有些...
    開(kāi)封第一講書(shū)人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)蟆融。 經(jīng)常有香客問(wèn)我草巡,道長(zhǎng),這世上最難降的妖魔是什么型酥? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任山憨,我火速辦了婚禮,結(jié)果婚禮上弥喉,老公的妹妹穿的比我還像新娘郁竟。我一直安慰自己,他們只是感情好由境,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布棚亩。 她就那樣靜靜地躺著,像睡著了一般虏杰。 火紅的嫁衣襯著肌膚如雪讥蟆。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,156評(píng)論 1 308
  • 那天纺阔,我揣著相機(jī)與錄音瘸彤,去河邊找鬼。 笑死州弟,一個(gè)胖子當(dāng)著我的面吹牛钧栖,可吹牛的內(nèi)容都是我干的低零。 我是一名探鬼主播婆翔,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼掏婶!你這毒婦竟也來(lái)了啃奴?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤雄妥,失蹤者是張志新(化名)和其女友劉穎最蕾,沒(méi)想到半個(gè)月后依溯,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡瘟则,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年黎炉,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片醋拧。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡慷嗜,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出丹壕,到底是詐尸還是另有隱情庆械,我是刑警寧澤,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布菌赖,位于F島的核電站缭乘,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏琉用。R本人自食惡果不足惜堕绩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望邑时。 院中可真熱鬧逛尚,春花似錦、人聲如沸刁愿。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)铣口。三九已至滤钱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間脑题,已是汗流浹背件缸。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留叔遂,地道東北人他炊。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像已艰,于是被迫代替她去往敵國(guó)和親痊末。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359